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 to merge json object with same keys?

Here are the 2 items in one array:

{
  "SysID": "12345",
  "Name": "abc"
}
{
  "SysID": "12345",
  "Name": "def"
}
{
  "SysID": "23456",
  "Name": "hij"
}
{
  "SysID": "23456",
  "Name": "klm"
}
{
  "SysID": "23456",
  "Name": "nop"
}

I would like to transform "SysID" into key and "Name" as the value of it in array:

{
  "12345": [
    "abc",
    "def",
  ],
  "23456": [
    "hij",
    "klm",
    "nop",
  ],
}

May I know how could I do that in jq?

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 :

Using reduce():

reduce .[] as $i ({}; .[$i.SysID] += [$i.Name])

WIll give

{
  "12345": [
    "abc",
    "def"
  ],
  "23456": [
    "hij",
    "klm",
    "nop"
  ]
}

When called with --slurp to wrap those object into an array


JqPlay 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