JQ合并2个json文件之间的新值

时间:2019-09-27 22:28:16

标签: json jq

我是JQ的新秀。

我想将2个json文件与JQ合并。但仅适用于第一个文件中的当前密钥。


第一个文件(first.json)

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

第二个文件(second.json)

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

我已经尝试过了。

编辑: 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 个答案:

答案 0 :(得分:2)

这是一排纸,它非常有效:

jq --argfile first first.json '. as $in | $first | with_entries(.value = $in[.key] )' second.json 

答案 1 :(得分:0)

考虑:

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"
}