提问人:gotothesky 提问时间:11/15/2023 更新时间:11/15/2023 访问量:49
我可以在 bash 中使用 jq 从 json 文件中提取和输出 EventId 吗?
Can I just extract and output EventId from json file using jq in bash?
问:
我的json文件如下。这是一个示例文件。
{
"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": [
]
}
我只想在上面的 json 文件中输出 EventId。 我尝试的如下,但我失败了。
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"
我非常感谢任何帮助过我的人。如果您能帮助我更进一步,我将不胜感激。
答:
1赞
pmf
11/15/2023
#1
您的输入是可以直接寻址的对象流。只需遍历数组的项,然后提取:.Events
.EventId
jq -r '.Events[].EventId' test.json
C7061BAC-AFDC-4513-B24B-AA5F13A16123
C7061BAC-AFDC-4513-B24B-AA5F13A16123
1赞
aazizzailani
11/15/2023
#2
您需要调整 jq 表达式以仅从 JSON 文件中提取 “EventId”。由于 JSON 结构在“事件”下包含数组,因此应使用以下命令:
cat test.json | jq -c '.Events[] | .EventId'
此命令将遍历“Events”数组中的每个元素,并从每个元素中提取“EventId”。输出将是“EventId”值的列表。
评论
.Events[].EventId