I have a json file with the following format
{"id": "3DFD4GF", "demographic": [{"country": "Spain", "rating": 7},{"country": "Germany", "rating": 2}]}
I want to see each line where country
is "Canada" and rating
is 10 in the same object within the demographic
array
I tried:
jq 'select((.demographic[].country=="Canada") and .demographic[].rating==10)' json
but this will return lines where inside the demographic
array there can be any object containing "country": "Canada"
and any object where "rating": 10
However, my goal is to have those two key value pairs in the same object
The expected output is:
{"id": "454FGF6", "demographic": [{"country": "Germany", "rating": 4},{"country": "Canada", "rating": 10}]}
How can I change my query to return the desired result?
>Solution :
Use any()
to check if any of the demographic
match your logic:
select(.demographic | any(.country == "Spain" and .rating == 7))
{
"id": "3DFD4GF",
"demographic": [
{
"country": "Spain",
"rating": 7
},
{
"country": "Germany",
"rating": 2
}
]
}