Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq - filter array does not contain

Tags:

json

jq

I'm using the application jq to filter json files from the command line.

https://stedolan.github.io/jq/

Here's a poor example that represents the problem. How do I filter this set to include all the fruits that are not red, or not round?

fruit.json:

[
  {
    "name": "banana",
    "tags": [
      "yellow",
      "long"
    ]
  },
  {
    "name": "apple",
    "tags": [
      "red",
      "round"
    ]
  },
  {
    "name": "orange",
    "tags": [
      "orange",
      "round",
      "colored"
    ]
  }
]

This finds all the red fruit:

jq '.[] | select(.tags[] == "red")' fruit.json

How do I find all the fruit that are not red?

Yes, I know in this example an array of tags for different purposes is not good design. The real world data has an array for good reason. I'm just looking for how to search for the records where the array does not contain a value.

This gives odd results, including duplicates which includes "apple" as "round" is not "red" so it matches.

jq '.[] | select(.tags[] != "red")' fruit.json

Suggestions?

like image 799
Tim Riker Avatar asked Mar 05 '23 00:03

Tim Riker


1 Answers

This should work:

jq '.[] | select(.tags | index("red") | not)' fruit.json

When you do .tags[], it will go through all the elements in array tags one by one, that's why you get duplicate results.

like image 146
Kamal Avatar answered Mar 14 '23 20:03

Kamal