sort by element in array using jq

Viewed 65

Given

[3,4]
[5,2]

I'd like to produce:

[5,2]
[3,4]

I tried this but it fails:

echo '[3,4] [5,2]' | jq 'sort_by(.[1])'

jq: error (at <stdin>:1): Cannot index number with number
jq: error (at <stdin>:1): Cannot index number with number
1 Answers

Use -n with inputs to access the stream's items. [‌...] collects them into an outer array, sort_by(...) sorts by criteria, ...[] decomposes the outer array again, and -c makes the output compact

jq -nc '[inputs] | sort_by(.[1])[]'
[5,2]
[3,4]

Demo

Related