Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace nested object with an object from another file in JQ

Tags:

json

jq

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

like image 505
user373201 Avatar asked Oct 23 '25 17:10

user373201


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 '.b = first(inputs, .b)' file1 file2
like image 110
oguz ismail Avatar answered Oct 26 '25 08:10

oguz ismail