Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jq select based on two conditions within one child object

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

JqPlay Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading