Skip to content

JSONPath Syntax

JSONPath is a query language used to navigate and extract data from JSON documents. It provides a concise and flexible syntax for specifying paths to specific nodes or values within JSON objects and arrays. The syntax of JSONPath is inspired by XPath, which is used for navigating XML documents.

Basic Syntax

The basic syntax of JSONPath consists of a combination of dot (.) and bracket ([]) notation, along with various operators and wildcards. Here's an overview of the key components:

  • Dot Notation (.): The dot notation is used to traverse through object properties. For example, $.name navigates to the name property of the root object.

  • Bracket Notation ([]): The bracket notation is used to access array elements or object properties with special characters or spaces in their names. For example, $['product name'] accesses the property with the name "product name".

  • Root Operator ($): The $ symbol denotes the root of the JSON document and is used to start a JSONPath expression.

Wildcards

JSONPath supports wildcards to match multiple elements within an array or object. The following wildcards are commonly used:

  • * (Asterisk): Matches all elements at the current level. For example, $.products[*] matches all elements in the products array.

  • .. (Double Dot): Recursive descent, matches all elements at any depth below the current level. For example, $..price matches all price properties in the JSON document.

Predicates

Predicates are used to filter elements based on certain conditions. Predicates are enclosed in square brackets ([]) and can contain comparison operators and values. Some common predicates include:

  • Index: [n] matches the element at index n within an array. Indexing is zero-based.

  • Slice: [start:end:step] matches a slice of elements within an array. The start, end, and step parameters are optional.

Functions

JSONPath supports functions for more advanced querying and manipulation. Functions are invoked using parentheses (()). Some common functions include:

  • length(): Returns the number of elements in an array or the length of a string.

  • min() and max(): Returns the minimum or maximum value from an array of numbers.

  • avg(): Calculates the average value from an array of numbers.

Examples

Here are some examples of JSONPath expressions:

  • $.store.book[*].author: Selects the author property of all books in the store object.

  • $.employees[?(@.age > 30)]: Selects all elements in the employees array where the age property is greater than 30.

  • $.people[0].friends.length(): Returns the number of friends for the first person in the people array.