jq · lesson 3 of 32 · Getting started
Array index & slice
Index arrays with [n] (zero-based; negative numbers count from the end) and slice them with [from:to] (the end is exclusive).
Examples
Example 1First, last and a range
Document
{ "langs": ["rust", "go", "c", "zig", "lua"] }Query
.langs[0], .langs[-1], .langs[1:3]
.langs[0]The first element (index 0) →"rust"..langs[-1]A negative index counts from the end → the last element,"lua"..langs[1:3]A slice from index 1 up to, but not including, 3 →["go","c"].
Result
"rust" "lua" ["go","c"]
Good to know
- Slices work on strings too, and either end may be left out:
.[:2]or.[2:].