根据jq中的多个值选择条目 [英] Select entries based on multiple values in jq

查看:137
本文介绍了根据jq中的多个值选择条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与JQ合作,到目前为止,我绝对喜欢它.不过,我遇到了一个问题,我尚未找到其他任何地方的解决方案,并想看看社区是否有办法做到这一点.

I'm working with JQ and I absolutely love it so far. I'm running into an issue I've yet to find a solution to anywhere else, though, and wanted to see if the community had a way to do this.

假设我们有一个看起来像这样的JSON文件:

Let's presume we have a JSON file that looks like so:

{"author": "Gary", "text": "Blah"}
{"author": "Larry", "text": "More Blah"}
{"author": "Jerry", "text": "Yet more Blah"}
{"author": "Barry", "text": "Even more Blah"}
{"author": "Teri", "text": "Text on text on text"}
{"author": "Bob", "text": "Another thing to say"}

现在,我们要选择author的值等于"Gary"或"Larry"的行,但没有其他情况.实际上,我要检查的名称有数千个,因此仅说明直接或条件(例如cat blah.json | jq -r 'select(.author == "Gary" or .author == "Larry")')是不够的.我正在尝试通过inside函数执行此操作,但出现一个错误对话框:

Now, we want to select rows where the value of author is equal to either "Gary" OR "Larry", but no other case. In reality, I have several thousand names I'm checking against, so simply stating the direct or conditional (e.g. cat blah.json | jq -r 'select(.author == "Gary" or .author == "Larry")') isn't sufficient. I'm trying to do this via the inside function like so but get an error dialog:

cat blah.json | jq -r 'select(.author | inside(["Gary", "Larry"]))'

jq: error (at <stdin>:1): array (["Gary","La...) and string ("Gary") cannot have their containment checked

做这样的事情的最佳方法是什么?

What would be the best method for doing something like this?

推荐答案

insidecontains有点奇怪.这里有一些更简单的解决方案:

inside and contains are a bit weird. Here are some more straightforward solutions:

select( .author as $a | ["Gary", "Larry"] | index($a) )

any/2

["Gary", "Larry"] as $whitelist
| select( .author as $a | any( $whitelist[]; . == $a) )

使用字典

如果性能是一个问题,并且如果作者"始终是一个字符串,则应考虑使用@JeffMercado建议的解决方案.这是一个变体(与-n命令行选项一起使用):

Using a dictionary

If performance is an issue and if "author" is always a string, then a solution along the lines suggested by @JeffMercado should be considered. Here is a variant (to be used with the -n command-line option):

["Gary", "Larry"] as $whitelist
| ($whitelist | map( {(.): true} ) | add) as $dictionary
| inputs
| select($dictionary[.author])

这篇关于根据jq中的多个值选择条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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