Avoid these 6 jq features
In this tutorial, we’ll discuss features of jq that will slow you down and how to move fast instead. jq is a powerful tool for any fast coder and by avoiding jq’s pitfalls, we’ll be even faster. This tutorial assumes a basic familiarity with jq and bash.
first, last, nth(n)
jq has 3 fabulously dangerous methods, first/last/nth(n) that break The Rule of Least Surprise. Don’t use them, instead, use simple filters.
Before/After
First
# Before: Using first with an expression
echo 10 | jq 'first(., .*2, .*3)'
# After: Using simple filters
echo 10 | jq '[., .*2, .*3][0]'
# Before: Using first without an expression
echo [2, 4, 6] | jq 'first'
# After: Using array index
echo [2, 4, 6] | jq '.[0]'
Last
# Before: Using last with an expression
echo 10 | jq 'last(., .*2, .*3)'
# After: Using simple filters
echo 10 | jq '[., .*2, .*3][-1]'
# Before: Using last without an expression
echo [2, 4, 6] | jq 'last'
# After: Using array index
echo [2, 4, 6] | jq '.[-1]'
nth(n)
# Before: Using nth with an ex…