【问题标题】:Find duplicates in JSON array在 JSON 数组中查找重复项
【发布时间】:2018-01-02 09:08:19
【问题描述】:

有人知道如何使用 jq 在 JSON 数组中查找重复项吗?

例如:

输入:

[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]

输出:

[{"foo": 1, "bar": 2}]

【问题讨论】:

    标签: json jq


    【解决方案1】:

    jq 中许多可能的解决方案之一:

    group_by(.) | map(select(length>1) | .[0])
    

    【讨论】:

    • 有没有办法在 jq 的 group_by 过滤器中使用多个键?
    • 是的,您可以使用任何 jq 表达式作为 group_by 的参数,例如[ .key1, .key2 ]。但正如其他地方所指出的,目前实现的group_by 对于大型数组来说效率很低,因为它涉及到排序。
    • 再次感谢Peak!
    【解决方案2】:

    涉及内置group_by 的解决方案涉及排序,因此如果目标只是识别重复项,则效率低下。这是一个无排序解决方案,它使用在此处定义的通用且强大的 bagof 函数在流上:

    # Create a two-level dictionary giving [item, n] where n
    # is the multiplicity of the item in the stream
    def bagof(stream):
      reduce stream as $x ({};
        ($x | [type, tostring]) as $key
        | getpath($key) as $entry
        | if $entry then setpath($key; [$x, ($entry[1] + 1 )])
          else setpath($key; [$x, 1])
          end ) ;
    
    # Emit a stream of duplicated items in the stream, s:
    def duplicates(s): bagof(s) | .[][] | select(.[1]>1) | .[0];
    
    # Input: an array
    # Output: an array of items that are duplicated in the array
    def duplicates: [duplicates(.[])];
    
    

    【讨论】:

      猜你喜欢
      • 2018-05-16
      • 2018-09-05
      • 2021-12-10
      • 2019-01-02
      相关资源
      最近更新 更多