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 question about parsing dictionaries within lists

I have a json file in the following format

{
  "a": [
    [
      {
        "p": "p1-value",
        "d": "d1-value"
      },
      {
        "p": "p2-value",
        "d": "d2-value"
      }
    ],
    [
      {
        "p": "p3-value",
        "d": "d3-value"
      }
    ]
  ],
  "z": [
    [
      {
        "p": "p1-value",
        "d": "d1-value"
      }
    ]
  ]
}

and I’d like to know how to output something like this

a p1-value
a p2-value
a p3-value
x p1-value

I’ve tried a few different jq queries but I can’t get it to work.

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

I know I can use ‘keys[]’ at the top level but that doesn’t give me anything below it. I’ve tried ."a" | .[] | .[] | .path but that means I have to specify each top level key..

Thanks

>Solution :

Either use to_entries to create an array of key-value pairs, which you can access by using .key and .value:

to_entries[] | "\(.key) \(.value[][].p)"

Demo

Or fetch just the keys using keys_unsorted, bind them to a variable using as, and access the fields using the variable:

keys_unsorted[] as $key | "\($key) \(.[$key][][].p)"

Demo

In both cases I used string interpolation "\(…)" to construct the final values, but depending on your processing pipeline, there might be better ways.

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