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?
JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.
We can merge two JSON arrays using the addAll() method (inherited from interface java. util.
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.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With