Select entries based on multiple values in jq

IRC user gnomon answered this on the jq channel as follows:

jq 'select([.author] | inside(["Larry", "Garry", "Jerry"]))'

The intuition behind this approach, as stated by the user was: "Literally your idea, only wrapping .author as [.author] to coerce it into being a single-item array so inside() will work on it." This answer produces the desired result of filtering for a series of names provided in a list as the original question desired.


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

index/1

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

any/2

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

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])

Tags:

Json

Whitelist

Jq