Replace nested object with an object from another file in JQ

Viewed 162

I have a json file that has the following structures

{
  "a":"aval",
  "b":{},
  "c":"cval"
}

I have another json file with following content

{
  "b1":"b1val","b2":"b2val"
}

I want to shove the json object from file 2 into "b" from file 1

{
  "a":"aval",
  "b":{
      "b1":"b1val","b2":"b2val"
  },
  "c":"cval"
}

how do i do this with JQ

1 Answers

Assuming file #2 may not be empty, you can simply assign input to .b.

jq '.b = input' file1 file2

Online demo

Otherwise you'd use the following to retain the original value of .b when file #2 is empty.

jq -n 'input | .b = first(inputs, .b)' file1 file2
Related