使用jq合并两个文件

时间:2019-08-24 12:20:12

标签: json jq

我有两个文件。

第一:

[
  { "person1": [] },
  { "person2": [] }
]

第二:

[
  {
    "person2": { "attribute1": "wer", "attribute2": "sdf" }
  },
  {
    "person2": { "attribute1": "ert", "attribute2": "dfg" }
  },
  {
    "person2": { "attribute1": "rty", "attribute2": "fgh" }
  },
  {
    "person3": { "attribute1": "tyu", "attribute2": "ghj" }
  },
  {
    "person1": { "attribute1": "yui", "attribute2": "hjk" }
  }
]

我尝试使用jq合并它们。对于第一个文件中的每个人(在第二个文件中,应该有更多人,应忽略这些人),创建其属性列表。因此输出应如下所示:

[
  {
    "person1":
      [
        { "attribute1": "yui", "attribute2": "hjk" }
      ]
  },
  {
    "person2":
      [
        { "attribute1": "wer", "attribute2": "sdf" },
        { "attribute1": "ert", "attribute2": "dfg" },
        { "attribute1": "rty", "attribute2": "fgh" }
      ]
  }
]

我尝试了其他选项,但无法达到预期的结果。

2 个答案:

答案 0 :(得分:2)

jq 'reduce (input[]|to_entries[]) as $e (add;
  if has($e.key) then .[$e.key] += [$e.value] else . end
) | [keys_unsorted[] as $k|{($k): .[$k]}]' file1 file2

online demo

答案 1 :(得分:1)

以下解决方案着重于效率,还提出了输出的另一种格式:

jq程序(merge.jq)

add as $dict
# aggregation:
| (reduce input[] as $record ({};
   ($record|keys_unsorted[0]) as $person
   | if $dict[$person] then .[$person] += [$record[$person]] else . end )) as $answer
# re-arrangement
| reduce ($dict|keys_unsorted[]) as $person ([]; . + [ {($person): $answer[$person] } ] )

调用

jq -f merge.jq first.json second.json