JQ:在一组值中选择具有键值的对象 [英] JQ: Select objects with key's value in set of values
问题描述
我有一个json对象数组,我想提取该数组的一个子集,以使.name
字段与一组输入字符串匹配.
I have an array of json objects and I would like to extract a subset of the array such that the .name
field matches a set of input strings.
例如,我想完成以下工作.
for example I would like to accomplish the following.
jq -n '["a","b","c","d","e"] | map({name:.,foo:"bar"})' \
| jq 'map(select(.name=="a" or .name=="c"))'
我已经提出了以下解决方案,但是我对[...]
和add
的用法似乎缺少一些聪明的东西.
I've come up with the following solution, but my usage of [...]
and add
seems like I am missing something clever.
jq -n '["a","b","c","d","e"] | map({name:.,foo:"bar"})' \
| jq --arg name 'a c' '
[
( $name | split(" ") )[] as $name
| map( select( .name == $name ) )
| add
]'
此外,此解决方案迫使我对输入数组进行多次迭代,而不是单次遍历.还有其他想法可以解决这个问题吗?
Also, this solution forces me to iterate over the input array multiple times instead of a single pass. Any other ideas how I could solve this?
推荐答案
将所有内容移至select
条件.您不需要对jq进行两个单独的调用.
Move everything into the select
condition. You don't need to do two separate calls to jq.
$ echo '["a","b","c","d","e"]' | jq --arg names 'a c'
'map(select(. == ($names | split(" ")[])) | { name: ., foo: "bar" })'
[
{
"name": "a",
"foo": "bar"
},
{
"name": "c",
"foo": "bar"
}
]
这篇关于JQ:在一组值中选择具有键值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!