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.
2
Answers
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
:Demo
You need to adjust the jq expression to extract only "EventId" from the JSON file. Since your JSON structure includes an array under "Events," you should use the following command:
This command will iterate through each element in the "Events" array and extract the "EventId" from each element. The output will be a list of "EventId" values.