🎓 A1Learner
🔍
0 of 45 lessons completed

Bash jq Filters

jq filters are expressions that keep, drop, or test values inside JSON. They run on each value in turn, so one filter can sift a whole array.

Keep matching items with select

The select test keeps only active users aged 30 or more. Bo is active but too young, and Cy is old enough but inactive, so both drop out.

printf '%s\n' '[{"name":"Ada","age":36,"active":true},{"name":"Bo","age":22,"active":true},{"name":"Cy","age":41,"active":false}]' | jq -r '.[] | select(.active and .age >= 30) | .name'

Filter by a number threshold

The test .price > 15 keeps only the dearer item. The cheaper item fails the test and prints nothing.

printf '%s\n' '[{"name":"Ada","price":10},{"name":"Bo","price":25}]' | jq -r '.[] | select(.price > 15) | .name'

Order results with sort_by

The sort_by(.age) step orders the items by age before the names print. The youngest name prints first, even though it sat last in the input.

printf '%s\n' '[{"name":"Cy","age":41},{"name":"Ada","age":36},{"name":"Bo","age":22}]' | jq -r 'sort_by(.age) | .[].name'

Example

printf '%s\n' '[{"name":"Cy","active":false},{"name":"Bo","active":true},{"name":"Ada","active":true}]' > team.json
jq -r 'map(select(.active)) | sort_by(.name) | .[].name' team.json

Key points

  • select: keeps only values where its test is true.
  • Comparison: ==, !=, <, and >= test numbers and strings inside select.
  • and / or: combine two tests in one select.
  • test: matches a string against a regular expression.
  • map: runs a filter on every array item and collects the results.
  • sort_by: orders array items by a field before printing them.

In this example, the script first writes a small team file with names out of order. The map step keeps only active members, so Cy drops out. The sort_by step orders the rest by name, so Ada prints before Bo.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which filter keeps only active users aged 30 or more?