如何使用数组的 jq 深度合并 2 个文件

How to deep merge 2 files with jq for arrays

我正在尝试合并以下两个 json 文件;但我似乎只能部分合并;一旦元素在数组中,reduce 就会失败。

{
    "value1": 200,
    "timestamp": 1382461861,
    "deployment": [
        {
            "component": "whatever",
            "containers": "key value"
        }
    ]
}

{
    "status": 200,
    "timestamp": 1382461861,
    "deployment": [
        {
            "autoscaling": {
                "maxReplicas": 1,
                "minReplicas": 1,
                "targetCPUUtilizationPercentage": 40
            }
        }
    ]
}

如果输入是数组,则使用 jq -s 'reduce .[] as $item({}; . * $item)' x.json x2.json 无效;相反,我得到了部分合并但没有深度合并

{
  "value1": 200,
  "timestamp": 1382461861,
  "deployment": [
    {
      "autoscaling": {
        "maxReplicas": 1,
        "minReplicas": 1,
        "targetCPUUtilizationPercentage": 40
      }
    }
  ],
  "status": 200
}

预期输出为

{
    "value1": 200,
    "timestamp": 1382461861,
    "deployment": [
        {
            "component": "whatever",
            "containers": "key value",

            "autoscaling": {
                "maxReplicas": 1,
                "minReplicas": 1,
                "targetCPUUtilizationPercentage": 40
            }
        }
    ],
    "status": 200,
}

谁能告诉我哪里可能出错了

看来您必须定义自己的“合并”过滤器。

根据您的示例输入,以下内容确实会产生您要求的结果,但在您完善规范时,应该将其作为起点:

def merge($a; $b): 
   if ($a|type) == "object" and ($b|type) == "object" 
       then reduce (($a + $b)|keys_unsorted[]) as $k ({}; 
         .[$k] = merge($a[$k]; $b[$k]))
   elif ($a|type) =="array" and ($b|type) == "array" then  $a + $b | add
   elif $b == null then $a
   else $b
   end;

为了提高效率,您可能希望考虑将其作为 merge(input;input) 调用,使用 -n 命令行选项而不是 -s。