代码之家  ›  专栏  ›  技术社区  ›  phear

如何在中合并(平均/求和)重复的对象。json通过jq?

  •  3
  • phear  · 技术社区  · 6 年前

    我正在试图消除有时出现在输入中的重复项。
    以下是数据示例:

    {
      "some": "very",
      "random": 0.228,
      "stuff": 31337,
      "people": [
        {
          "name": "carl",
          "height": "180cm",
          "wifes": 1,
          "sons": 0
        },
        {
          "name": "charlie",
          "height": "166cm",
          "wifes": 0,
          "sons": 2
        },
        {
          "name": "carl",
          "height": "180cm",
          "wifes": 1,
          "sons": 1
        },
        {
          "name": "carl",
          "height": "195cm",
          "wifes": 1.95,
          "sons": 12
        }
      ]
    }
    

    有很多carl,但只有两个是重复的-名称:carl&高度:180cm。
    例如,我需要计算他妻子的平均数和儿子的总数。
    以下是预期结果:

    [
      {
        "name": "carl",
        "height": "180cm",
        "wifes": 1,
        "sons": 3
      },
      {
        "name": "charlie",
        "height": "166cm",
        "wifes": 0,
        "sons": 2
      },
      {
        "name": "carl",
        "height": "195cm",
        "wifes": 1.95,
        "sons": 12
      }
    ]
    

    我试着使用“add”和“reduce”,但我对jq>相当陌生<

    1 回复  |  直到 6 年前
        1
  •  3
  •   peak    6 年前

    分组可通过以下方式实现 group_by/1 使用[.名称,.高度]作为分组标准:

    def sum(f): map(f) | add;
    
    def average(f): sum(f) / length;
    
    def consolidate:
      .[0]
      + {wifes: average(.wifes)}
      + {sons:  sum(.sons) } ;
    
    .people
    | group_by([.name,.height])
    | map(consolidate)
    

    输出

    输出符合给定的描述性要求:

    [
      {
        "name": "carl",
        "height": "180cm",
        "wifes": 1,
        "sons": 1
      },
      {
        "name": "carl",
        "height": "195cm",
        "wifes": 1.95,
        "sons": 12
      },
      {
        "name": "charlie",
        "height": "166cm",
        "wifes": 0,
        "sons": 2
      }
    ]