Merging two JSON objects with jq

时间:2017-11-08 22:09:31

标签: json object merge 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?

3 个答案:

答案 0 :(得分:6)

通过传入多个输入文件,每个文件的内容都会流入。您可能需要将它们插入或组合各个输入。

$ jq -s 'add' file1 file2

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

或者如果你想合并而不是添加。

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

答案 1 :(得分:1)

jq --slurpfile选项的替代方式:

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

输出:

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

答案 2 :(得分:1)

这是另一种方式(假设file1.jsonfile2.json中的示例数据):

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