All articles

JSONPath: querying JSON data without manual parsing

JSONPath is a query language for pulling values out of a JSON document by path, the same job XPath does for XML — except most JSON API responses today are deep enough that "just read it" stops working past a couple of nesting levels.

Basic syntax

An expression always starts with $, the document root. From there, fields are reached with a dot ($.user.name) or bracket notation ($['user']['name']), and array elements by index ($.items[0]).

Selecting more than one value at once

The * wildcard selects every element at a given level, while .. is recursive descent — it finds a field at any depth regardless of the exact path to it. Filters like [?(@.price < 10)] select array elements by a condition that reads like a small programming expression.

Why this comes up

  • Pulling one field out of a large API response while debugging, without writing a script.
  • Filtering JSON logs or events by a condition on the fly.
  • Reading a value out of a config file without hand-rolling a parser.

JSONPath vs. XPath: the off-by-one that trips people up

Anyone coming from XPath, where array-like node indexing starts at 1 (book[1] is the first item), tends to get bitten moving to JSONPath, where indexing starts at 0 — book[1] is already the second element. That single difference accounts for a surprising share of bugs when older XML/XPath-based integrations get ported to JSON APIs.

Keys with dots or spaces

If a field name itself contains a dot, hyphen, or space (say, a literal key "user.name" rather than nested fields), dot notation like $.user.name becomes ambiguous — the parser reads it as the nested fields user and name. In that case the key has to go in quoted brackets instead: $['user.name'].

Try the tool