0

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?

5

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"
    }
  ]
}
2

In contrast to RomanPerekhrest's solution, this will allow you merge the target field without remaking the entire object:

jq -s '.[0].attributes = [.[].attributes | add] | .[0]' file*.json

This returns the entirety of the first json file with the .attributes from all the others concatenated together.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.