Issue
My json file is as follows. This is a sample file.
{
"DocumentIncarnation": 1,
"Events": [
]
}
{
"DocumentIncarnation": 2,
"Events": [
{
"EventId": "C7061BAC-AFDC-4513-B24B-AA5F13A16123",
"EventStatus": "Scheduled",
"EventType": "Freeze",
"ResourceType": "VirtualMachine",
"Resources": [
"WestNO_0",
"WestNO_1"
],
"NotBefore": "Mon, 11 Apr 2022 22:26:58 GMT",
"Description": "Virtual machine is being paused because of a memory-preserving Live Migration operation.",
"EventSource": "Platform",
"DurationInSeconds": 5
}
]
}
{
"DocumentIncarnation": 3,
"Events": [
{
"EventId": "C7061BAC-AFDC-4513-B24B-AA5F13A16123",
"EventStatus": "Started",
"EventType": "Freeze",
"ResourceType": "VirtualMachine",
"Resources": [
"WestNO_0",
"WestNO_1"
],
"NotBefore": "",
"Description": "Virtual machine is being paused because of a memory-preserving Live Migration operation.",
"EventSource": "Platform",
"DurationInSeconds": 5
}
]
}
{
"DocumentIncarnation": 4,
"Events": [
]
}
I want to output only EventId in the json file above. What I tried is as follows, but I failed.
cat test.json | jq -c '.[] | [.EventId]'
jq: error (at <stdin>:5): Cannot index number with string "EventId"
jq: error (at <stdin>:25): Cannot index number with string "EventId"
jq: error (at <stdin>:45): Cannot index number with string "EventId"
jq: error (at <stdin>:51): Cannot index number with string "EventId"
I am deeply grateful to anyone who helps me. I'd appreciate it if you could help me grow one step further.
Solution
Your input is a stream of objects which you can address directly. Just iterate over the items of the .Events
array, and extract the .EventId
:
jq -r '.Events[].EventId' test.json
C7061BAC-AFDC-4513-B24B-AA5F13A16123
C7061BAC-AFDC-4513-B24B-AA5F13A16123
Answered By - pmf Answer Checked By - Pedro (WPSolving Volunteer)