有没有办法可以使用jq查找包含与给定条件匹配的值的所有路径?
例如,给定以下JSON,我想返回“age”的值> 35的所有路径,而不管包含该字段的结构的深度如何:
{
"springfield":{
"marge":{
"age":30
},
"homer":{
"age":40,
"job":"xyz"
}
},
"shelbyville":{
"zone1":{
"john":{
"age":10
}
},
"zone2":{
"mark":{
"age":50
}
}
},
"homeless1":{
"age":25
},
"homeless2":{
"age":60
}
}
因此执行会产生类似:
[
["springfield", "homer"],
["shelbyville", "zone2", "mark"],
["homeless2"]
]
答案 0 :(得分:2)
以下测试使用jq 1.4和jq 1.5:
$ jq -M -c '(paths | select(.[length-1] =="age")) as $path
| if (getpath($path) > 35) then $path else empty end' ages.json
["springfield","homer","age"]
["shelbyville","zone2","mark","age"]
["homeless2","age"]
以下要求jq 1.5:
$ jq -c --stream 'select(length == 2 and .[0][-1] == "age"
and .[1] > 35)' ages.json
[["springfield","homer","age"],40]
[["shelbyville","zone2","mark","age"],50]
[["homeless2","age"],60]
这些都可以很容易地适应产生类似的输出。