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

How tabulize nested JSON lists using jq in bash

I would like to parse data from a JSON-file into a tsv-file, but I cannot make it work.

Input

{
  "images": [
    {
      "id": "592a77a5-614e-4ed8-b846-d4db1f27edbf",
      "name": "ubuntu",
      "tags": [
        "latest"
      ]
    },
    {
      "id": "592da7a5-614e-4ed8-b846-d4db1f27edbf",
      "name": "debian",
      "tags": [
        "latest",
        "10.0"
      ]
    }   
  ]
}

Desired output

The desired output is a tab-separated table

ubuntu    latest
debian    latest
debian    10.0

What I have tried

# My data
echo '{"images":[{"id":"592a77a5-614e-4ed8-b846-d4db1f27edbf","name":"ubuntu","tags":["latest"]},{"id":"592da7a5-614e-4ed8-b846-d4db1f27edbf","name":"debian","tags":["latest","10.0"]}]}' > my.json

# My query
jq -r '.images | map({id} + (.tags | fromjson[])) | @tsv' my.json > my.tsv

First I access the images-list, then I want to make an operation over all ids, where I want the tags. I borrowed the map from a similar post, but it does not seem to work. The only difference between my query and theirs is the extra layer with the .images.

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

>Solution :

Save the name into a variable before you go down to the tags

jq -r '.images[] | .name as $name | .tags[] | [$name, .] | @tsv'
ubuntu  latest
debian  latest
debian  10.0

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