Reputation: 13
I have the two following json files.
file1.json
{"field1":{"item1":0,"array1":[0,0,0],"array2":[0,0],"array3":[0]},"field2":{"dummy":0}}
file2.json
{"field1":{"item1":1,"array1":[1,1,1],"array2":[1,1],"array3":[1]},"field2":{"dummy":0}}
I want to obtain this :
{"field1":{"item1":0,"array1":[0,0,0,1,1,1],"array2":[0,0,1,1],"array3":[0,1]},"field2":{"dummy":0}}
I am able to do it manually array by array but I would prefer a method to do it automatically for each array of field1. Does someone have a tip for me ?
Thanks a lot for your help !
Upvotes: 1
Views: 77
Reputation: 117077
The following assumes that file1.json and file2.json contain valid JSON. You can convert the quasi-JSON to JSON using jq by running: jq -n -f fileN.json
def extend_arrays(o):
reduce keys[] as $k
(.; if (.[$k]|type) == "array" and (o[$k]|type == "array")
then .[$k] += o[$k] else . end);
.field1 |= extend_arrays($second|.field1)
With these lines in the file program.jq, the invocation:
jq -c --argfile second file2.json -f program.jq file1.json
produces the required output:
{"field1":{"item1":0,"array1":[0,0,0,1,1,1],"array2":[0,0,1,1],"array3":[0,1]},"field2":{"dummy":0}}
Upvotes: 1