如何在不重新排序的情况下使用jq从json流中删除重复的对象



这是您的输入数据:"3""5""2""2"
计算一个jq查询以返回"3""5""2"
我的用例:轮询第三方服务状态的JSON对象,它的更改频率比我轮询的要低。

我尝试了jq -n '[inputs] | unique[]',但这会重新排序结果。

这在jq Cookbook中有介绍。以下是摘录,省略了定义uniques/1:所不需要的两个def

使用bag实现unique的无分类版本

jq的unique内置了一个排序,在实践中它通常足够快,但对于非常大的数组,或者如果处理非常长的实体流,或者如果第一次出现的顺序很重要,则可能不需要。一种解决方案是使用";袋";,即多重集意义上的多重集。这里有一个面向流的实现,它保留了通用性,并利用了jq在JSON对象中查找的实现:


# bag(stream) uses a two-level dictionary: .[type][tostring]
# So given a bag, $b, to recover a count for an entity, $e, use
# $e | $b[type][tostring]
def bag(stream):
reduce stream as $x ({}; .[$x|type][$x|tostring] += 1 );

现在定义uniques(流(是一个简单的问题;s";这里是合适的,因为过滤器产生一个流:


# Produce a stream of the distinct elements in the given stream
def uniques(stream):
bag(stream)
| to_entries[]
| .key as $type
| .value
| to_entries[]
| if $type == "string" then .key else .key|fromjson end ;

最新更新