问题描述
我正在尝试使用 JQ 在这种 json 中返回父级:
{
"all" : {
"text": "a","children": [
{
"text": "aa","children": []
},{
"text": "ab",{
"text": "ac","children": [
{
"text": "aca","children": []
},{
"text": "acb",{
"text": "acc","children": [
{
"text": "acca","children": []
}
]
}
]
}
]
}
}
目标是检索元素的父文本。 例如:
此代码不起作用:
.all | .children[] as $parent | select(.children[].text == "acca" ) | $parent.text
有人可以帮助我吗? 谢谢! :)
解决方法
这很容易。获取您要查找的字符串的路径,从中检索到其祖父母的路径,然后从中提取 text
。
getpath(
paths(strings
| select(. == "acca")
)[:-3]
) .text
,
这是一个简洁的参数化解决方案,不需要显式使用 recurse
:
paths(objects | select(.text == $needle)) as $p
| getpath($p[:-2]).text
示例用法:
jq --arg needle acca -f program.jq input.json
(注意可能不需要引用“needle”。)