jq搜索值并返回标量

huangapple go评论60阅读模式
英文:

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(&quot;name&quot;)) .name)

<sup>Online demo</sup>

huangapple
  • 本文由 发表于 2023年3月31日 23:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定