使用选择将对象列入白名单 [英] Whitelisting objects using select

查看:83
本文介绍了使用选择将对象列入白名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jq提供的contains函数过滤列表. 我的输入

I'm trying to filter lists using contains function, provided by jq. My input,

[1, 2, 3, 4, 5]

我有一个白名单" :

[3, 4, 7]

我需要通过白名单过滤输入列表. 预期的产量:

I need to filter input list through whitelist. Expected output:

[3, 4]

我能够过滤比较单个项目:

I'm able to filter comparing a single item:

jq --compact-output --null-input '[1,2,3,4,5] | map(select(. | contains(3)))'
[3]

我尝试过:

$ jq --compact-output --null-input '[1,2,3,4,5] | map(select([3,4,7] | contains([.])))'
[]
$

在这里[3,4,7] | contains([.])提出问题的意图:

Here [3,4,7] | contains([.]) intents to pose question:

[.]是列表[3,4,7]的子列表吗?

is [.] a sublist of list [3,4,7]?

但是它不起作用.我想念什么?

But it doesn't work. What am I missing?

如何使用白名单进行过滤?

推荐答案

要与contains一起使用的过滤器是:

The filter you'd use with contains is:

map(. as $x | select([3,4,7] | contains([$x])))

您的尝试使用.错误地.

Your attempt uses . incorrectly.

对于这种类型的问题,使用index/1可能比contains或它的反本inside更好.原因既有语义方面的,也有效率方面的.

For this type of problem, it might be better to use index/1 than contains or its inverse, inside. The reasons stem from both semantic and efficiency considerations.

如果白名单可以用作$ whitelist,并且要使用map(select(...)),则合适的过滤器为:

If the whitelist is available as $whitelist and if you want to use map(select(...)), an appropriate filter would be:

map( . as $x | select($whitelist|index($x)))

对于长数组,这当然效率很低.对于这样的数组,您几乎肯定会想要看看替代方法,例如使用bsearch(二进制搜索)或JSON对象(哈希).

For long arrays, this of course is very inefficient. For such arrays, you will almost surely want to look at alternatives, such as using bsearch (binary search), or a JSON object (hash).

index/1的当前实现对于当前目的而言并不理想,但是由于它是用C语言编写的,因此实现起来很快.这是一个替代定义,它假定any/2的可用性:

The current implementation of index/1 is less than ideal for the present purpose, but it is fast because it is written in C. Here's an alternative definition that assumes the availability of any/2:

def ix(x): any(.[]; .==x);

这篇关于使用选择将对象列入白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆