JSONPath Array Index — Access Elements by Position

Access specific array elements in JSONPath using index notation. Learn zero-based indexing, negative indices, and practical examples for JSON arrays.

Array Operations

Detailed Explanation

Array Index Access in JSONPath

Array indexing in JSONPath uses square brackets with a numeric index to access elements at specific positions. Indices are zero-based, meaning the first element is at index 0.

Syntax

$.array[0]       // first element
$.array[1]       // second element
$.array[-1]      // last element
$.array[-2]      // second to last

Positive Indices

Given:

{
  "fruits": ["apple", "banana", "cherry", "date", "elderberry"]
}
  • $.fruits[0] returns "apple"
  • $.fruits[2] returns "cherry"
  • $.fruits[4] returns "elderberry"

Negative Indices

Negative indices count from the end of the array:

  • $.fruits[-1] returns "elderberry" (last element)
  • $.fruits[-2] returns "date" (second to last)
  • $.fruits[-5] returns "apple" (same as index 0 for a 5-element array)

Nested Array Access

For multi-dimensional data:

{
  "matrix": [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
}
  • $.matrix[0][0] returns 1 (top-left)
  • $.matrix[1][2] returns 6 (second row, third column)
  • $.matrix[-1][-1] returns 9 (bottom-right)

Out of Bounds

When the index exceeds the array length, most implementations return an empty result set rather than throwing an error. This is a key difference from many programming languages.

Index vs. Slice vs. Filter

Method Syntax Returns
Index [2] Single element
Slice [0:3] Range of elements
Filter [?(@.active)] Elements matching condition

Array indexing is the simplest and most efficient way to grab a known element from an ordered list.

Use Case

Use array indexing when you need a specific element from an ordered collection — for example, the latest log entry (index -1), the first search result (index 0), or accessing matrix coordinates in numerical datasets.

Try It — JSON Path Evaluator

Open full tool