首页 > 解决方案 > 使用 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" }
      ]
  }
]

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

标签: jsonjq

解决方案


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

在线演示


推荐阅读