jq-如何基于属性值的“白名单"选择对象 [英] jq - How to select objects based on a 'whitelist' of property values

查看:58
本文介绍了jq-如何基于属性值的“白名单"选择对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为一个例子值一千个单词,所以说我有以下JSON流:

Since an example is worth a thousand words, say I have the following JSON stream:

{"a": 0, "b": 1}
{"a": 2, "b": 2}
{"a": 7, "b": null}
{"a": 3, "b": 7}

如何保留.b属性是[1, 7]之一的所有对象(实际上,列表长得多,所以我不想做select(.b == 1 or .b == 7)).我正在寻找这样的东西:select(.b in [1, 7]),但是我在手册页中找不到我想要的东西.

How can I keep all the objects for which the .b property is one of [1, 7] (in reality the list is much longer so I don't want to do select(.b == 1 or .b == 7)). I'm looking for something like this: select(.b in [1, 7]), but I couldn't find what I'm looking for in the man page.

推荐答案

可以使用模式select($value == $collection[])实现$value in $collection. select(any($value == $collection[]; .))是更有效的替代方法,因此您的过滤器应为:

Doing $value in $collection could be achieved using the pattern select($value == $collection[]). A more efficient alternative would be select(any($value == $collection[]; .)) So your filter should be this:

[1, 7] as $whitelist | select(any(.b == $whitelist[]; .))

将数组包含在变量中有其好处,因为它使您可以使用参数轻松更改白名单.

Having the array in a variable has its benefits as it lets you change the whitelist easily using arguments.

$ jq --argjson whitelist '[2, 7]' 'select(any(.b == $whitelist[]; .))'

这篇关于jq-如何基于属性值的“白名单"选择对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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