Merging many json files into one by merging it into a common object

jqjson

I have many json files of such format:

sample file1:

{
  "attributes": [
    {
      "name": "Node",
      "value": "test"
    }
  ]
}

sample file2:

{
  "attributes": [
    {
      "name": "version",
      "value": "11.1"
    }
  ]
}

etc.

I need to merge all of them to one json file, eg.

{
  "attributes": [
    {
      "name": "Node",
      "value": "test"
    },
    {
      "name": "version",
      "value": "11.1"
    }
  ]
}

Could someone please provide a solution with jq?

Best Answer

jq solution:

jq -s '{ attributes: map(.attributes[0]) }' file*.json
  • -s (--slurp) - instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.

Sample output:

{
  "attributes": [
    {
      "name": "Node",
      "value": "test"
    },
    {
      "name": "version",
      "value": "11.1"
    }
  ]
}
Related Question