0

I need to merge two JSON files into one. The requirement is to replace values of keys existing in both files by values from second file. And add keys doesn't exist in first should be appended to the output JSON.

Is it possible to use jq to perform this operation?

First JSON:

{
    "foo": "bar",
    "aaa": "aaa",
    "count": 0
}

Second JSON:

{
    "bbb": "bbb",
    "count": 1
}

Expected output:

{
    "foo": "bar",
    "aaa": "aaa",
    "count": 1,
    "bbb": "bbb"
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 3
    `jq '. + input' first.json second.json` (use `*` instead of `+` if you need nesting). – pmf Mar 09 '22 at 15:41
  • 1
    Or `jq -s add first.json second.json`. – chepner Mar 09 '22 at 15:43
  • 1
    (Interestingly, `jq -n 'input + input' first.json second.json` does *not* work; it seems to read `second.json` first.) – chepner Mar 09 '22 at 15:44
  • Another answer is here: https://stackoverflow.com/questions/19529688/how-to-merge-2-json-objects-from-2-files-using-jq – fukanchik Mar 09 '22 at 15:44
  • @chepner - jq and gojq differ in the order of evaluation of the arguments to `+`. For jq you could write: `input as $a | $a + input` – peak Mar 09 '22 at 19:02

1 Answers1

-1

jq provides “object multiplication” feature:

jq '. * input' file1.json file2.json

See the manual:

Multiplication, division, modulo: *, /, and %

[…]

Multiplying two objects will merge them recursively: this works like addition but if both objects contain a value for the same key, and the values are objects, the two are merged with the same strategy.

jiwopene
  • 3,077
  • 17
  • 30