JQ, чтобы объединить новые значения между 2 файлами JSON - PullRequest
0 голосов
/ 28 сентября 2019

Я новичок с JQ.

Я хотел бы объединить 2 файла JSON с JQ.Но только для настоящих ключей в первом файле.


Первый файл (first.json)

{
  "@@locale": "en",
  "foo": "bar1"
}

Второй файл (second.json)

{
  "@@locale": "en",
  "foo": "bar2",
  "oof": "rab"
}

Я уже пробовал.

edit: jq -n '. [0]*. [1] 'first.json second.json

jq -s '.[0] * .[1]' first.json second.json

Но возвращенный результат неверен.

{
  "@@locale": "en",
  "foo": "bar2",
  "oof": "rab"
}

Запись "oof" не должна присутствовать.


Ожидаемое объединение.

{
  "@@locale": "en",
  "foo": "bar2"
}

С уважением.

Ответы [ 2 ]

2 голосов
/ 28 сентября 2019

А вот одна строка, которая оказывается весьма эффективной:

jq --argfile first first.json '. as $in | $first | with_entries(.value = $in[.key] )' second.json 
0 голосов
/ 28 сентября 2019

Рассмотрим:

jq -n '.
  | input as $first         # read first input
  | input as $second        # read second input
  | $first * $second        # make the merger of the two the context item
  | [ to_entries[]          # ...then break it out into key/value pairs
    | select($first[.key])  # ...and filter those for whether they exist in the first input
  ] | from_entries          # ...before reassembling into a single object.
' first.json second.json

... который правильно излучает:

{
  "@@locale": "en",
  "foo": "bar2"
}
...