JSONPath in JavaScript, Python and Java: Parse and Query JSON in Code
You have a JSONPath expression that works in a tester, and now you need it in your code. This guide shows how to parse JSON and run JSONPath queries in JavaScript, Python, Java and on the command line, with tested code and the real output. It also covers the small differences between libraries that make an expression work in one place and fail in another.
The example data
All examples read this file, saved as data.json:
{
"orders": [
{ "id": 101, "customer": "Ann", "status": "paid", "total": 25.5 },
{ "id": 102, "customer": "Ben", "status": "pending", "total": 99 },
{ "id": 103, "customer": "Cara", "status": "paid", "total": 140 }
]
}JavaScript and Node.js: jsonpath-plus
JavaScript has no built-in JSONPath. The most used library is jsonpath-plus. It works in Node.js and in the browser.
npm install jsonpath-plusimport { JSONPath } from 'jsonpath-plus'
import { readFileSync } from 'node:fs'
// 1. Parse the JSON text into an object
const data = JSON.parse(readFileSync('data.json', 'utf8'))
// 2. Run the query
const names = JSONPath({ path: '$.orders[*].customer', json: data })
console.log(names) // [ 'Ann', 'Ben', 'Cara' ]
const paidIds = JSONPath({ path: "$.orders[?(@.status == 'paid')].id", json: data })
console.log(paidIds) // [ 101, 103 ]Useful options:
// Get one value instead of an array
JSONPath({ path: '$.orders[0].customer', json: data, wrap: false })
// → 'Ann'
// Get the paths of the matches instead of the values
JSONPath({ path: '$.orders[?(@.total > 50)]', json: data, resultType: 'path' })
// → [ "$['orders'][1]", "$['orders'][2]" ]
// Array length
JSONPath({ path: '$.orders.length', json: data })
// → [ 3 ]result.name is undefined, but result[0].name works. Use wrap: false if you expect exactly one value.Python: jsonpath-ng
In Python, use jsonpath-ng. Note that it has two parsers: the basic one, and an extended one in jsonpath_ng.ext that you need for filters and len.
pip install jsonpath-ngimport json
from jsonpath_ng.ext import parse # the "ext" parser supports filters
# 1. Parse the JSON file into a dict
with open("data.json") as f:
data = json.load(f)
# 2. Compile the expression once, then run it
names = [m.value for m in parse("$.orders[*].customer").find(data)]
print(names) # ['Ann', 'Ben', 'Cara']
paid = [m.value for m in parse("$.orders[?(@.status == 'paid')].id").find(data)]
print(paid) # [101, 103]
# Where was each match found?
print([str(m.full_path) for m in parse("$.orders[?(@.total > 50)]").find(data)])
# ['orders.[1]', 'orders.[2]']
# Array length uses `len` (with backticks)
print([m.value for m in parse("$.orders.`len`").find(data)]) # [3]from jsonpath_ng import parse (without .ext) and use a filter, you get JsonPathLexerError: Unexpected character: ?. Switch to from jsonpath_ng.ext import parse..find() returns match objects, not plain values. Read .value for the data and .full_path for where it was found. If you run the same expression many times, call parse() once and reuse the result: parsing is the slow part.
Java: Jayway JsonPath
In Java and Kotlin, the standard choice is Jayway JsonPath (com.jayway.jsonpath:json-path). It is also what Spring's jsonPath() test helpers use.
import com.jayway.jsonpath.JsonPath;
import java.util.List;
String json = Files.readString(Path.of("data.json"));
List<String> names = JsonPath.read(json, "$.orders[*].customer");
// [Ann, Ben, Cara]
List<Integer> paid = JsonPath.read(json, "$.orders[?(@.status == 'paid')].id");
// [101, 103]
int count = JsonPath.read(json, "$.orders.length()");
// 3If you query the same document many times, parse it once with JsonPath.parse(json) and call .read(...) on the result. In Jayway, the array length is .length() with parentheses.
Command line: kubectl and jq
kubectl has JSONPath built in. Its syntax wraps the expression in curly braces and leaves out the $:
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'For any other JSON on the command line, jq is the usual tool. It does not use JSONPath, but the ideas map one to one:
| JSONPath | jq |
|---|---|
$.orders[0].customer | .orders[0].customer |
$.orders[*].customer | .orders[].customer |
$.orders[-1] | .orders[-1] |
$.orders[?(@.status == 'paid')].id | .orders[] | select(.status == "paid") | .id |
$.orders.length | .orders | length |
$..id | .. | .id? // empty |
See the jq cheat sheet for many more examples.
Why the same expression gives different results
JSONPath was only standardized in 2024 (RFC 9535). Libraries written before that differ in small ways:
| Feature | jsonpath-plus (JS) | jsonpath-ng (Python) | Jayway (Java) |
|---|---|---|---|
| Filters | Yes | Only with jsonpath_ng.ext | Yes |
| Array length | .length | .`len` | .length() |
| Result for one match | Array (or value with wrap: false) | List of match objects | Value for a definite path, list otherwise |
| Regex in filters | @.name.match(/x/) | @.name =~ "x" | @.name =~ /x/ |
Tip: keep production expressions simple (paths, [*], [0] and plain comparisons). Those work the same everywhere.
A quick way to find the right path
- Open your JSON in the JSON Viewer, click the value you need and press Copy path.
- Paste it into the JSONPath Tester and turn it into a general query, for example by changing
[2]to[*]or adding a filter. - Copy the final expression into the code from this guide.
For more expression examples, see JSONPath array examples and the JSONPath tutorial.