Jq: select only an array that contains element A, but not element B

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

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

How, using jq, I only select arrays that contain the element with the "first source" as the name value, but which does not contain the "second_source" as the name value for any element?

This returns only the element for further processing:

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

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

+4
source share
1 answer

You can use this filter:

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

. , any all.

, - "first_source", "second_source".

+5

All Articles