Merging two JSON objects with jq

Viewed 9508

I have two json files, each containing one simple object, for example:

file1

{
    "key1": "value1",
    "key2": "value2"
}

file2

{
    "key1": "valueA",
    "key3": "valueB"
}

I need to combine these two using jq so that I end up with one object that contains all of the keys from both objects. If there are common keys, I need the values of from second object being used.

I'm struggling to get the right expression to use. I thought that something as simple as

jq '. * .' file1 file2

should give me what I want, however this results in a non-json output:

{
    "key1": "value1",
    "key2": "value2"
}
{
    "key1": "valueA",
    "key3": "valueB"
}

The same exact thing happens if I use jq '. + .' file1 file2.

How can I combine these two objects?

3 Answers

By passing in multiple input files, the contents of each file are streamed in. You'd either have to slurp them in or combine the individual inputs.

$ jq -s 'add' file1 file2

or

$ jq -n 'reduce inputs as $i ({}; . + $i)' file1 file2

Or if you wanted to merge instead of add.

$ jq -n 'reduce inputs as $i ({}; . * $i)' file1 file2

Alternative way with jq --slurpfile option:

jq --slurpfile f2 file2 '. + $f2[0]' file1

The output:

{
  "key1": "valueA",
  "key2": "value2",
  "key3": "valueB"
}

Here is another way (assumes sample data in file1.json and file2.json):

$ jq -Mn --argfile file1 file1.json --argfile file2 file2.json '$file1 + $file2'
{
  "key1": "valueA",
  "key2": "value2",
  "key3": "valueB"
}
Related