JQ question about parsing dictionaries within lists

44 views Asked by At

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
z p1-value

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

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

1

There are 1 answers

1
pmf On BEST ANSWER

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.