简体   繁体   中英

jq: select only an array which contains element A but not element B

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"
  }
]

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)
)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM