【问题标题】:Count and remove duplicates in jq计算并删除 jq 中的重复项
【发布时间】:2017-10-19 11:37:56
【问题描述】:

我有一个对象数组,我想删除这个数组中的一些重复项,但我想保留重复项的数量。

我的输入是:

[
    {
        "foo": 1,
        "bar": "a",
        "baz": "whatever"
    },
    {
        "foo": 1,
        "bar": "a",
        "baz": "hello"
    },
    {
        "foo": 1,
        "bar": "b",
        "baz": "world"
    }
]

(不确定它是否重要,但对象的唯一性基于foobar,而不是baz

所需输出的示例如下:

[
    {
        "foo": 1,
        "bar": "a",
        "baz": "whatever",
        "count": 2
    },
    {
        "foo": 1,
        "bar": "b",
        "baz": "world",
        "count": 1
    }
]

甚至:

[
    {
        "count": 2,
        "data": {
            "foo": 1,
            "bar": "a",
            "baz": "whatever"
        }
    },
    ...
]

我知道如何做唯一性部分(unique_by([.foo, .bar])),但不知道计数部分。

【问题讨论】:

    标签: json jq


    【解决方案1】:

    可以基于group_by使用如下命令:

    group_by(.foo,.bar)
    | map(.[]+{"count":length})
    | unique_by(.foo,.bar)
    

    输出:

    [
      {
        "foo": 1,
        "bar": "a",
        "baz": "whatever",
        "count": 2
      },
      {
        "foo": 1,
        "bar": "b",
        "baz": "world",
        "count": 1
      }
    ]
    

    你提到的其他输出可以用这个命令来实现:

    group_by(.foo,.bar)
    | map({"count":length,"data":(unique_by(.foo,.bar)[])})
    

    输出:

    [
      {
        "count": 2,
        "data": {
          "foo": 1,
          "bar": "a",
          "baz": "whatever"
        }
      },
      {
        "count": 1,
        "data": {
          "foo": 1,
          "bar": "b",
          "baz": "world"
        }
      }
    ]
    

    【讨论】:

    • 谢谢,它有效!对于第二个输出,做"data": first不是更简单吗?
    • 是的,也可以使用。而且会更简单!
    • 哦,是的!已删除。
    • 在任何一个答案中都不需要 unique_by ,例如对于第一种方法,以下内容就足够了: group_by(.foo,.bar) |地图(。[0]+{计数:长度})。第二个:group_by(.foo,.bar) | map({"count":length,"data": .[0]})
    【解决方案2】:

    这是一个解决方案,它使用peakGROUPS_BY 而不是group_by/1 来避免排序:

    def GROUPS_BY(stream; f): reduce stream as $x ({}; .[$x|f] += [$x] ) | .[] ;
    
      GROUPS_BY(.[]; {foo,bar}|tostring)
    | .[0].count = length
    | .[0]
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      • 2021-03-21
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多