skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. You can also use group_by to merge

    jq 'group_by(.SysID)|map({(.[0].SysID): map(.Name)})|add'
    
    $ jq 'group_by(.SysID)'    
    [
      [{"SysID":"12345","Name":"abc"},{"SysID":"12345","Name":"def"}],
      [{"SysID":"23456","Name":"hij"},{"SysID":"23456","Name":"klm"},{"SysID":"23456","Name":"nop"}]
    ]
    
    $ jq 'group_by(.SysID)|map({(.[0].SysID): map(.Name)})'
    [
      {"12345":["abc","def"]},
      {"23456":["hij","klm","nop"]}
    ]
    
    $ jq 'group_by(.SysID)|map({(.[0].SysID): map(.Name)})|add'
    {
      "12345": [
        "abc",
        "def"
      ],
      "23456": [
        "hij",
        "klm",
        "nop"
      ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search