使用相同的键合并对象数组

时间:2020-06-10 07:25:17

标签: json jq

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

这是一个人为设计的示例,试图说明该问题:

来自

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

收件人

{
  "google.com": {
    "http": {
      "dest_url": "http://stackoverflow.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"
    }
  }
}

2 个答案:

答案 0 :(得分:2)

使用reduce*运算符进行递归合并的更短选择:

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

demo at jqplay.org

答案 1 :(得分:1)

您可以在执行group_by()后使用键名的to_entries()并从分组结果中形成最终的JSON

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

请参见jq-play