JQ:在一组值中选择具有键值的对象 [英] JQ: Select objects with key's value in set of values

查看:68
本文介绍了JQ:在一组值中选择具有键值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆