使用 JQ 获取 JSON 中某个键的所有值的数组 [英] Get array with all values for certain key in JSON wih JQ
问题描述
假设我有以下 JSON:
Say I have the following JSON:
{
"a": 0,
"b": "c",
"d": {
"e": {
"f": "g",
"comments": {
"leading": "Lorem ipsum"
},
"h": {
"i": {
"j": [
1,
2
]
},
"comments": {
"trailing": "dolor sit"
}
}
},
"comments": {
"leading": "amet."
}
}
}
我想获得一个数组,其中包含名为 comments
的所有字段的值(可以嵌套在任何级别).所以,在这种情况下,我想得到:
I want to get an array with the values of all the fields named comments
(which can be nested in any level). So, in this case I want to get:
[
{
"leading": "Lorem ipsum"
},
{
"trailing": "dolor sit"
},
{
"leading": "amet."
}
]
数组的顺序无关紧要.
如何使用 jq
实现这一点?我只用它进行了基本的操作,并没有产生任何接近我需要的东西.
How can this be achieved with jq
? I have only performed basic stuff with it and haven't been able to produce anything close to what I need.
提前谢谢☺️
推荐答案
您可以使用 getpath
函数.使用 paths
识别所有通向 .comments
的路径并获取路径的值
You can use the getpath
function. Use paths
to identify all the paths leading upto .comments
and get the paths' value
jq '[ getpath ( paths | select( .[-1] == "comments" ) ) ]'
或者使用递归下降过滤包含.comments
的对象并获取其值
Or use a recursive descent to filter objects containing .comments
and get its value
jq '[ recurse | select(has("comments")?).comments ]'
这篇关于使用 JQ 获取 JSON 中某个键的所有值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!