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

Parse an array of json object using jq

I am trying to parse the below json file and store the result into another json file. How do I achieve this ?

{
  "Objects": [
    {
      "ElementName": "Test1",
      "ElementArray": ["abc","bcd"],
      "ElementUnit": "4"
    },
    {
      "ElementName": "Test2",
      "ElementArray": ["abc","bcde"],
      "ElementUnit": "8"
    }
  ]
}

Expected result :

{
"Test1" :[
"abc","bcd"
],
"Test2" :[
"abc","bcde"
]
}

I’ve tried something on the lines of the below but I seem to be off –

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 '[.Objects[].ElementName ,(.Objects[]. ElementArray[])]' user1.json

jq ".Objects[].ElementName .Objects[].ElementArray" ruser1.json

>Solution :

Your expected output needs to be wrapped in curly braces in order to be a valid JSON object. That said, use from_entries to create an object from an array of key-value pairs, which can be produced by accordingly mapping the input object’s Objects array.

.Objects | map({key: .ElementName, value: .ElementArray}) | from_entries
{
  "Test1": [
    "abc",
    "bcd"
  ],
  "Test2": [
    "abc",
    "bcde"
  ]
}

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