【发布时间】:2018-01-02 09:08:19
【问题描述】:
有人知道如何使用 jq 在 JSON 数组中查找重复项吗?
例如:
输入:
[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]
输出:
[{"foo": 1, "bar": 2}]
【问题讨论】:
有人知道如何使用 jq 在 JSON 数组中查找重复项吗?
例如:
输入:
[{"foo": 1, "bar": 2}, {"foo": 1, "bar": 2}, {"foo": 4, "bar": 5}]
输出:
[{"foo": 1, "bar": 2}]
【问题讨论】:
jq 中许多可能的解决方案之一:
group_by(.) | map(select(length>1) | .[0])
【讨论】:
[ .key1, .key2 ]。但正如其他地方所指出的,目前实现的group_by 对于大型数组来说效率很低,因为它涉及到排序。
涉及内置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(.[])];
【讨论】: