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 combine jq array value into same key in json file in shell script?

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

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

  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.

>Solution :

You’re looking for transpose.

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

Online 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