JSONPath Array Slice — Select Ranges of Elements
Use JSONPath array slicing [start:end:step] to extract ranges of elements. Learn syntax, step values, and practical examples for working with JSON arrays.
Array Operations
Detailed Explanation
Array Slicing in JSONPath
Array slicing extracts a range of elements from an array using the [start:end:step] syntax. It is inspired by Python's slice notation and provides a concise way to select contiguous or evenly spaced elements.
Syntax
$.array[start:end] // elements from start to end-1
$.array[start:end:step] // with step interval
$.array[:end] // from beginning to end-1
$.array[start:] // from start to the end
$.array[::step] // every Nth element
Basic Slicing
Given:
{
"numbers": [10, 20, 30, 40, 50, 60, 70, 80]
}
$.numbers[0:3]returns[10, 20, 30]— first three elements$.numbers[2:5]returns[30, 40, 50]— elements at index 2, 3, 4$.numbers[-3:]returns[60, 70, 80]— last three elements$.numbers[:4]returns[10, 20, 30, 40]— first four elements
Using Step
The step parameter controls the interval between selected elements:
$.numbers[::2]returns[10, 30, 50, 70]— every other element$.numbers[1::2]returns[20, 40, 60, 80]— every other element starting from index 1$.numbers[::-1]returns[80, 70, 60, 50, 40, 30, 20, 10]— reversed array (in implementations that support negative step)
Slice Parameters
| Parameter | Default | Description |
|---|---|---|
start |
0 | Beginning index (inclusive) |
end |
array length | Ending index (exclusive) |
step |
1 | Interval between elements |
Practical Patterns
- Pagination:
$.items[0:10]for first page,$.items[10:20]for second page. - Head/Tail:
$.items[:5](first 5) and$.items[-5:](last 5). - Sampling:
$.data[::10]to grab every 10th record for quick analysis.
Use Case
Use array slicing for pagination of JSON data, extracting recent entries from log arrays, sampling large datasets for preview, or implementing head/tail operations on ordered collections.