How to combine jq array value into same key in json file in shell script?

Viewed 67

I have a json file with this content:

[
  {
    "id": "one",
    "msg": [
      "test"
    ],
    "FilePath": [
      "JsonSerializer.cs",
      "ChatClient.cs",
      "MiniJSON.cs"
    ],
    "line": [
      358,
      1241,
      382
    ]
  },
  {
    "id": "two",
    "msg": [
      "secondtest"
    ],
    "FilePath": [
      "Utilities.cs",
      "PhotonPing.cs"
    ],
    "line": [
      88,
      36
    ]
  }
]

I want the output where as you can see the value combine into one :

one
[
  "test"
]
[
  "JsonSerializer.cs",358
  "ChatClient.cs",1241
  "MiniJSON.cs",382
]

two
[
  "secondtest"
]
[
  "Utilities.cs",88
  "PhotonPing.cs",36
]

I have tried this cat stack.json |jq -r '.[]|.id,.msg,.FilePath,.line' which gave output as

  one
    [
      "test"
    ]
    [
      "JsonSerializer.cs",
      "ChatClient.cs",
      "MiniJSON.cs"
    ]
    [
      358,
      1241,
      382
    ]
    two
    [
      "secondtest"
    ]
    [
      "Utilities.cs",
      "PhotonPing.cs"
    ]
    [
      88,
      36
    ]

Kindly help me resolve this, I have tried a lot to debug this but unable to get through. Also, the Filepath and line would always be similar for each . For example if FilePath has 3, line would also have 3 values.

2 Answers

You're looking for transpose.

.[] | .id, .msg, ([.FilePath, .line] | transpose | add), ""

Online demo

<stack.json jq -r '.[] | .id, .msg, ([.FilePath, .line]|transpose|add)'

gives the output as required by you.

transpose turns [[1,2,3],[4,5,6]] into [[1,4],[2,5],[3,6]] and add collects all array elements into a single array.

If you are looking to have file path and line number in a single line, I suggest formatting them as string, separated by colon:

.[] | .id, .msg, ([.FilePath, .line]|transpose|map(join(":")))
Related