【问题标题】:How to deep merge 2 files with jq for arrays如何将 2 个文件与数组的 jq 深度合并
【发布时间】:2021-04-01 15:37:52
【问题描述】:

我正在尝试合并以下两个 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,
}

谁能告诉我哪里出错了

【问题讨论】:

    标签: json object merge jq array-merge


    【解决方案1】:

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

    鉴于您的示例输入,以下确实会产生您要求的结果,但在您完善规范时,它可能应该作为起点:

    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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 2022-06-11
      • 2019-06-23
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多