我有一些 json(包含在下面),第一个键是一个随机数(docker 镜像 ID),所以在解析 json 之前我不知道它是什么。
我想做的是
cat eval.json | jq \
'."3193328829c7b3ec6be0ab6bfd8988b97a35006ea578c9ce4ab7fe29cbc5ec94".result.rows[] | select (.[2]=="stop")'
这工作得很好,但我需要在我提前不知道图像 ID 的一般情况下执行此操作。
我尝试了这个,除了我收到一些“无法索引”错误之外,这种方法有效:
cat eval.json | jq .[] | jq '.result.rows[] | select (.[2]=="stop")'
[
"CVE-2021-3156+sudo",
"HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
"stop",
false
]
jq: error (at <stdin>:33): Cannot index array with string "result"
jq: error (at <stdin>:34): Cannot index string with string "result"
jq: error (at <stdin>:35): Cannot index array with string "result"
jq: error (at <stdin>:36): Cannot index array with string "result"
一点点改进有助于解决数组问题,但我仍然遇到字符串错误:
cat eval.json | jq '.[].result.rows[] | select (.[2]=="stop")'
[
"CVE-2021-3156+sudo",
"HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
"stop",
false
]
jq: error (at <stdin>:38): Cannot index array with string "result"
我可以删除最后四个键(我认为我永远不会需要它们来完成我想做的事情),但这似乎是一个非常笨拙的黑客。
cat eval.json | jq 'del(.whitelist_names, .whitelist_data, .policy_name, .policy_data) | .[].result.rows[] | select ((.[2]=="stop") and (.[3]==false)) | .[0], .[1]'
"CVE-2021-3156+sudo"
"HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)"
有什么比使用 del 来清除这些键更好的方法吗?似乎如果有某种方法可以像数组中的第 N 个元素一样指定第一个键,那就容易多了。我想到的另一个想法是做一些尴尬的事情,比如打印出键,在变量中捕获长字符串,然后使用它直接选择该键,但这比删除其他键更麻烦。
下面是完整的 json:
{
"3193328829c7b3ec6be0ab6bfd8988b97a35006ea578c9ce4ab7fe29cbc5ec94": {
"result": {
"final_action": "stop",
"header": [
"Trigger_Id",
"Check_Output",
"Gate_Action",
"Whitelisted"
],
"row_count": 3,
"rows": [
[
"41cb7cdf04850e33a11f80c42bf660b3",
"Dockerfile directive 'HEALTHCHECK' not found, matching condition 'not_exists' check",
"warn",
false
],
[
"CVE-2018-20839+libudev1",
"MEDIUM Vulnerability found in os package type (dpkg) - libudev1 (CVE-2018-20839 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2018-20839)",
"warn",
false
],
[
"CVE-2021-3156+sudo",
"HIGH Vulnerability found in os package type (dpkg) - sudo (fixed in: 1.8.31-1ubuntu1.2)(CVE-2021-3156 - http://people.ubuntu.com/~ubuntu-security/cve/CVE-2021-3156)",
"stop",
false
]
]
}
},
"policy_data": [],
"policy_name": "",
"whitelist_data": [],
"whitelist_names": []
}
最佳答案
添加一个或多个“?”将是解决该问题的一种方法:
.[].result?.rows[] | select (.[2]=="stop")
如果要指定第一个键,请使用keys_unsorted[0]
,如下所示:
.[keys_unsorted[0]].result.rows[] | select (.[2]=="stop")
关于json - 无法使用字符串 "foo"索引字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66294487/