jq select input based on values in array

Viewed 220

I have a list of country codes like FR, IT, DE and have been trying to figure out how to use this in a select statement. I was doing something like

cat stuff | jq -c '.[]| select(.country_iso3166_alpha2 == "US")'

But then my list grew to a large number of countries I want to match on. So I tried using IN since I'm using jq 1.6 and did something like this:

eu=("FR", "IT"); cat stuff | jq -c '.[]| select(.country_iso3166_alpha2 IN($eu)'

I've been reading the docs and looking at the cookbook but it's not making any sense to me. Thanks!

2 Answers

You can use --argjson to pass the list to jq and IN to select the matching entries.

jq -c --argjson eu '["FR", "IT"]' '.[]| select(.country_iso3166_alpha2 | IN($eu[]))' <stuff

Broken out to show the individual parts:

jq -c \ 
    --argjson eu '["FR", "IT"]' \ 
    '.[]| select(.country_iso3166_alpha2 | IN($eu[]))' \ 
    <stuff
  1. invoke jq with compact output
  2. pass in the list of countries as a json array named "eu"
  3. select using the IN operator, unpacking $eu[] to get its values
  4. redirect the input file into jq

Unfortunately, jq does not understand bash arrays.

Things would probably be simplest if you can arrange to have your shell variable be a string representing a JSON array:

eu='["FR", "IT"]'
jq -n --argjson eu "$eu" '$eu'

Or if you prefer:

eu='["FR", "IT"]' jq -n 'env.eu | fromjson'

Another possibility would be to write your bash array into a file, and then slurp the file.

There are also many variants of the above....

Related