jq:仅选择一个包含元素A但不包含元素B的数组 [英] jq: select only an array which contains element A but not element B

查看:97
本文介绍了jq:仅选择一个包含元素A但不包含元素B的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据是一系列JSON数组.每个数组都有一个或多个带有名称和ID键的元素:

My data is a series of JSON arrays. Each array has one or more elements with name and id keys:

[
  {
    "name": "first_source",
    "id": "abcdef"
  },
  {
    "name": "second_source",
    "id": "ghijkl"
  },
  {
    "name": "third_source",
    "id": "opqrst"
  }
]

如何使用jq仅选择包含以"first source"作为名称值的元素但不包含"second_source"作为任何元素的名称值的数组?

How, using jq, do I select only the arrays which contain an element with "first source" as the name value, but which don't contain "second_source" as the name value of any element?

这只会返回一个元素进行进一步处理:

This only returns an element for further processing:

jq '.[] | select (.name == "first_source") 

但是我显然需要返回整个数组,以使方案正常工作.

But I clearly need to return the entire array for my scenario to work.

推荐答案

您可以使用以下过滤器:

You can use this filter:

select(
    (map(.name == "first_source") | any) and
    (map(.name != "second_source") | all)
)

您需要测试数组的所有元素是否存在名称.您可以通过将每个对象映射到您的条件并适当地使用anyall过滤器来做到这一点.

You need to test all the elements of an array for an existence of the names. You can do that by mapping each object to your condition and use the any or all filter appropriately.

在这里,您想查看是否有任何项目被命名为"first_source",而所有项目都没有被命名为"second_source".

Here, you want to see if any item is named "first_source" and all items are not named "second_source".

这篇关于jq:仅选择一个包含元素A但不包含元素B的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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