
- Arrays are zero-indexed: the first element is index 0.
- You can select a single element or multiple specific elements by index.
Different JSONPath engines vary in how they return single matches. Some return the raw value (e.g.,
"Apple"), while others return a singleton array (e.g., ["Apple"]). For consistency, the examples in this lesson show array-wrapped outputs. When integrating JSONPath in scripts, check how your library or tool returns matches.- Use the slice syntax
$[start:end]to select a contiguous range of elements. - This follows the common convention: include
startand excludeend(select indices start through end-1).
- Add a third value to the slice to specify a step:
$[start:end:step]. - A
stepof2selects every second element (skip one element between selections).
- Some implementations accept negative indices in slices. Negative indices count from the end:
-1is the last element,-2is the second-to-last, etc. - Using a single negative index like
$[-1]may or may not be supported across engines. - A more portable form is a slice-style negative index:
$[-1:]selects the last element and is accepted by more implementations. - Similarly,
$[-3:]returns the last three elements.
JSONPath engines implement features differently. To maximize portability across libraries and tools, prefer slice-style negative indices (e.g.,
$[-1:], $[-3:]) rather than relying on single negative-index syntax like $[-1].
Practice tips
- Try these queries against your own JSON or use online testers such as Jayway’s JSONPath evaluator or jsonpath.com to observe how different engines return results.
- When writing scripts, check the library’s API docs for return types and supported syntaxes.
- Jayway JSONPath (Java) — https://github.com/json-path/JsonPath
- JSONPath.com — https://jsonpath.com/
- JSONPath on Wikipedia — https://en.wikipedia.org/wiki/JSONPath