在JSON和JQ中获取具有特定键的所有值的数组 [英] Get array with all values for certain key in JSON wih JQ
本文介绍了在JSON和JQ中获取具有特定键的所有值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下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 ]'
这篇关于在JSON和JQ中获取具有特定键的所有值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文