How do I extract a key with jq based on its child values

匆匆过客 提交于 2020-06-09 05:40:45

问题


I'm trying to process some JSON with jq. Specifically, I want a particular key, based on its child value. Example, given:

{
  "foo": {"primary": true, "blah": "beep"},
  "bar": {"primary": false, "blah": "narf"},
  "baz": {"primary": false, "blah": "poink"},
}

I want the string "foo", because that is the key whose child value "primary' is true. (I can guarantee that one and only one entry will have primary = true, due to what's generating the JSON.)

So far the best I've been able to manage is:

jq -r '.[] | select(.primary == true)'

But that returns the value of "foo", not the string "foo" itself. Digging through the manual so far I've not found a way to grab the key specifically.

Any pointers you can provide?


回答1:


You need to "split" your object into an array of entries, e.g.

[
  {
    "key": "foo",
    "value": {
      "primary": true,
      "blah": "beep"
    }
  }
  //...
]

Then you can filter with .value.primary and map the result with .key:

to_entries | map(select(.value.primary)  | .key)

Returns:

[
  "foo"
]

Or to get just the first item of the array: (Thanks @nbari)

to_entries | map(select(.value.primary)  | .key)[0]


来源:https://stackoverflow.com/questions/62031471/how-do-i-extract-a-key-with-jq-based-on-its-child-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!