Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two JSON objects with jq

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?

like image 787
Aleks G Avatar asked Nov 08 '17 22:11

Aleks G


People also ask

How do I merge two JSON objects?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.

How do I combine two JSON responses?

We can merge two JSON arrays using the addAll() method (inherited from interface java. util.

How do I link two JSON files?

If you want to combine JSON files into a single file, you cannot just concatenate them since you, almost certainly, get a JSON syntax error. The only safe way to combine multiple files, is to read them into an array, which serializes to valid JSON.


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
like image 69
Jeff Mercado Avatar answered Sep 27 '22 19:09

Jeff Mercado


Alternative way with jq --slurpfile option:

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

The output:

{
  "key1": "valueA",
  "key2": "value2",
  "key3": "valueB"
}
like image 21
RomanPerekhrest Avatar answered Sep 27 '22 19:09

RomanPerekhrest


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"
}
like image 42
jq170727 Avatar answered Sep 27 '22 19:09

jq170727