【问题标题】:Merging array of objects with the same key合并具有相同键的对象数组
【发布时间】:2020-06-10 07:25:17
【问题描述】:

问题: 我有 N 个对象数组,它们在对象中具有相同的标识键,我很想将它们与 jq 合并。

这是一个人为的例子,试图说明问题:

来自

[
  {
    "google.com": {
      "http": {
        "dest_url": "http://*.com"
      }
    }
  },
  {
    "google.com": {
      "https": {
        "dest_url": "https://github.com"
      }
    }
  },
  {
    "test.com": {
      "https": {
        "dest_url": "https://wikipedia.com"
      }
    }
  }
]

收件人

{
  "google.com": {
    "http": {
      "dest_url": "http://*.com"
    },
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "test.com": {
    "https": {
      "dest_url": "https://wikipedia.com"
    }
  }
}

我尝试使用jq '. | add' file,但结果如下。

{
  "google.com": {
    "https": {
      "dest_url": "https://github.com"
    }
  },
  "test.com": {
    "https": {
      "dest_url": "https://wikipedia.com"
    }
  }
}

【问题讨论】:

    标签: json jq


    【解决方案1】:

    使用reduce* 运算符的递归合并的更短的替代方案:

    reduce .[] as $p ({}; . * $p)
    

    demo at jqplay.org

    【讨论】:

      【解决方案2】:

      你可以在to_entries()之后使用keyname的group_by(),并从分组结果中形成最终的JSON

      map(to_entries[])
      | group_by(.key)[] 
      | { (.[0].key) : map(.value)|add }
      

      看到它在jq-play上工作

      【讨论】: