如何根据子项的jq值提取密钥 [英] How do I extract a key with jq based on its child values
问题描述
我正在尝试使用jq处理一些JSON.具体来说,我想要一个基于其子值的特定键.示例,给出:
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"},
}
我想要字符串"foo",因为这是其子值"primary"为true的键(由于生成的是JSON,因此我可以保证只有一个条目的primary = true.)
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)'
但这将返回"foo"的值,而不是字符串"foo"本身.到目前为止,我一直在仔细阅读手册,但仍未找到一种方法来专门抓住钥匙.
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?
推荐答案
您需要将对象拆分"为条目数组,例如
You need to "split" your object into an array of entries, e.g.
[
{
"key": "foo",
"value": {
"primary": true,
"blah": "beep"
}
}
//...
]
然后您可以使用.value.primary
进行过滤,并使用.key
映射结果:
Then you can filter with .value.primary
and map the result with .key
:
to_entries | map(select(.value.primary) | .key)
返回:
[
"foo"
]
或者只获取数组的第一项:(谢谢@nbari)
Or to get just the first item of the array: (Thanks @nbari)
to_entries | map(select(.value.primary) | .key)[0]
这篇关于如何根据子项的jq值提取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!