如何在Bash中使用jq从JSON文件提取EventId?
提取JSON文件中的EventId问题解决
问题场景
我有一个包含多个JSON对象的文件(内容如下),希望仅提取其中的EventId:
{ "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": [ ] }
尝试执行以下命令时失败:
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"
问题原因
命令里的.[]会遍历顶级对象的所有属性,包括数值类型的DocumentIncarnation,而数值无法用字符串EventId索引,因此触发报错。另外EventId并非在顶级对象中,而是嵌套在Events数组的元素内,路径定位错误。
解决方法
使用以下命令可正确提取所有非空的EventId:
cat test.json | jq -r '.Events[]?.EventId'
参数说明:
.Events[]:遍历每个JSON对象中的Events数组?:跳过空的Events数组,避免无元素时触发报错.EventId:提取数组元素中的EventId字段-r:输出原始字符串格式,不带JSON引号
如果需要对结果去重,可追加unique处理:
cat test.json | jq -r '.Events[]?.EventId' | unique
内容的提问来源于stack exchange,提问作者gotothesky
相关产品推荐
相关产品推荐

