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 transform JSON doc

I have JSON file with below format

{
    "key1": ["val1", "val2"],
    "key2": ["v1", "v2"]
}

I want to transform it into

{
    "key1": ["val1-v1", "val2-v2"],
    "key2": ["v1", "v2"]
}

How can I acheive this using jq in linux environment?

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 :

You could use to_entries to generate an array of indices and values. Use the indices to index into the other key, stored in a variable for reference:

jq '. as {$key2} | .key1 |= [to_entries[] | .value + "-" + $key2[.key]]' data.json

Demo

If the arrays aren’t big, you could also use the less efficient transpose filter to zip them:

jq '.key1 = [map(.) | transpose[] | join("-")]' data.json

Demo

Output of both:

{
  "key1": [
    "val1-v1",
    "val2-v2"
  ],
  "key2": [
    "v1",
    "v2"
  ]
}
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