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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With