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: repeat value from one object when iterating through array elements in another object

Input:

{
  "level1": {
    "id": "a"
  },
  "level2": [
    {
      "id": "1"
    },
    {
      "id": "2"
    }
  ]
}
{
  "level1": {
    "id": "b"
  },
  "level2": [
    {
      "id": "3"
    },
    {
      "id": "4"
    }
  ]
}

Expected output:

a  1 
a  2 
b  3 
b  4 

What I basically want to accomplish is:

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

jq -r '[ .level1.id, (.level2[] |.id ) ]|@tsv'

where .level1.id repeats for every object in the .level2 array but I don’t seem to be able to think about the problem the right way

>Solution :

Using .level2[] within another array constructor (the outer […]) just collects all items iterated over into that constructed array. Separate them to iterate outside another array, make both parts create (sub)arrays themselves, then add them together:

[.level1.id] + (.level2[] | [.id]) | @tsv

Demo

Alternatively, use variables which you can reference from inside the array constructor:

.level2[] as {$id} | [.level1.id, $id] | @tsv

Demo

Output:

a   1
a   2
b   3
b   4
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