jsonmergekeyjq

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?


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