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

transform json input using jq command

I have the following json input from a internet service:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": [
    {
      "id": "test1",
      "products": [
        "product1",
        "product2"
      ],
      "description": "test1 description"
     },
     {
      "id": "test2",
      "products": [
        "product3",
        "product4",
        "product5"
      ],
      "description": "test2 description"
     },
     {
      "id": "test3",
      "products": [
        "product6",
        "product7",
        "product8"
      ],
      "description": "test2 description"
      }
   ]
}

So I need to transform profile key from array to json object. This is the desired output:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": {
      "test1": [
        "product1",
        "product2"
      ],
      "test2": [
        "product3",
        "product4",
        "product5"
      ],
      "test3": [
        "product6",
        "product7",
        "product8"
      ]
   }
}

I don’t have any idea how to do it in jq command, please, could you help me?

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

Thanks in advance.

>Solution :

Use with_entries which lets you convert the array into an object if you adjust the .keys accordingly.

jq '.profile |= with_entries(.key = .value.id | .value |= .products)'

Demo

Or use reduce to build the object by iterating through the array.

jq '.profile |= reduce .[] as $p ({}; .[$p.id] = $p.products)'

Demo

Or use map to convert each array item into an object, then merge them using add.

jq '.profile |= (map({(.id): .products}) | add)'

Demo

Output is:

{
  "sunarme": "foo",
  "id": "foo-id",
  "name": "Foo bar",
  "profile": {
    "test1": [
      "product1",
      "product2"
    ],
    "test2": [
      "product3",
      "product4",
      "product5"
    ],
    "test3": [
      "product6",
      "product7",
      "product8"
    ]
  }
}
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