Вопрос:

Merging two JSON objects with jq

json object merge jq

2213 просмотра

3 ответа

44879 Репутация автора

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?

Автор: Aleks G Источник Размещён: 08.11.2017 10:09

Ответы (3)


6 плюса

98545 Репутация автора

Решение

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
Автор: Jeff Mercado Размещён: 08.11.2017 10:16

1 плюс

65216 Репутация автора

Alternative way with jq --slurpfile option:

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

The output:

{
  "key1": "valueA",
  "key2": "value2",
  "key3": "valueB"
}
Автор: RomanPerekhrest Размещён: 08.11.2017 10:18

1 плюс

5782 Репутация автора

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"
}
Автор: jq170727 Размещён: 09.11.2017 12:13
Вопросы из категории :
32x32