英文:
jq search for value and return scalar
问题
我是一个jq新手,正在努力摸索它的用法。
我想要搜索JSON对象中具有特定名称的任何键,并提取第一次出现的值,以将其分配给bash变量以备后用。例如,使用:
{
"fruit":{
"name":"apple","color":"green","sub":{
"name":"crab-apple","color":"red","size":"small"
}
}
}
如果我使用:
jq -r 'map(.name)|.[0]?'
我得到我要找的输出,具体来说是"apple"。另一方面,
jq -r 'map(.size)|.[0]?'
导致
[
null
]
不是标量值,也不是我想要找到的。
英文:
I'm a newbie with jq and struggling to bend it to my will.
I want to search a JSON object for any key with a given name and extract the value for the first occurrence in order to assign this to a bash variable for later use. e.g. with:
{
"fruit":{
"name":"apple","color":"green","sub":{
"name":"crab-apple","color":"red","size":"small"
}
}
}
If I use:
jq -r 'map(.name)|.[0]?'
I get the output I am looking for, specifically "apple". OTOH
jq -r 'map(.size)|.[0]?'
results in
[
null
]
Not a scalar value and not what I wanted to find.
Please don't tell me I should search based on other attributes or the structure of JSON object (unless you're going to explain how to do a depth-first vs breadth-first search).
答案1
得分: 2
你正在寻找这样的东西:
first(recurse | objects | select(has("name")) .name)
<sup>在线演示</sup>
英文:
You're looking for something like this:
first(recurse | objects | select(has("name")) .name)
<sup>Online demo</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论