Home > Software design >  How to combine 2 JSON objects into one with jq?
How to combine 2 JSON objects into one with jq?

Time:12-16

I have two JSON objects in two files (result_0.json and result_1.json) which look like this

{
  "data": {
    "pools": [
      {
        "id": "1"
      },
      {
        "id": "2"
      }
    ]
  }
}

and like this:

{
  "data": {
    "pools": [
      {
        "id": "3"
      },
      {
        "id": "4"
      }
    ]
  }
}

What I would like to get looks like this:

{
  "data": {
    "pools": [
      {
        "id": "1"
      },
      {
        "id": "2"
      },
      {
        "id": "3"
      },
      {
        "id": "4"
      }
    ]
  }
}

How can it be done? I tried

jq -s add result_0.json result_1.json 

but it just overwrites the values in result_0.json with the values of result_1.json.

CodePudding user response:

If .data and .pool are the only keys in the json files, you can use

jq -n '{ data: { pools: [inputs.data.pools] | add } }' result0 result1

This will create the desired output:

{
  "data": {
    "pools": [
      {
        "id": "1"
      },
      {
        "id": "2"
      },
      {
        "id": "3"
      },
      {
        "id": "4"
      }
    ]
  }
}

Regarding the inputs keyword, consider reading JQ's docs on this part.

  • Related