JQ:Select 个在值集中具有键值的对象

JQ: Select objects with key's value in set of values

我有一个 json 对象数组,我想提取数组的一个子集,以便 .name 字段匹配一组输入字符串。

例如,我想完成以下操作。

jq -n '["a","b","c","d","e"] | map({name:.,foo:"bar"})' \
  | jq 'map(select(.name=="a" or .name=="c"))'

我想出了以下解决方案,但我对 [...]add 的使用似乎遗漏了一些聪明的东西。

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
      ]'

此外,此解决方案迫使我多次遍历输入数组,而不是单次遍历。还有其他解决办法吗?

将所有内容移至 select 条件。您不需要对 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"
  }
]

ThorSummoner点, 这是一个使用 --argjsoninside 的 perl-esqe 解决方案 在利用 shell ' 行为的单独行上发表评论:

$ echo '["a","b","c","d","e"]' | jq --argjson wanted '["a","c"]' '
  .[]                          # break array into elements
| if ([.]|inside($wanted))     # if element is in wanted
  then {name: ., foo:"bar"}    # generate desired output
  else empty                   # otherwise generate nothing
  end
'