Skip to main content

RFC 9535 JSONPath: Query Expressions for JSON in Python

We follow RFC 9535 strictly and test against the JSONPath Compliance Test Suite.

License Tests
PyPi - Version Python versions


Table of Contents

Install

Install Python JSONPath RFC 9535 using pip:

pip install jsonpath-rfc9535

Or Pipenv:

pipenv install -u jsonpath-rfc9535

Example

import jsonpath_rfc9535 as jsonpath

data = {
    "users": [
        {"name": "Sue", "score": 100},
        {"name": "Sally", "score": 84, "admin": False},
        {"name": "John", "score": 86, "admin": True},
        {"name": "Jane", "score": 55},
    ],
    "moderator": "John",
}

for node in jsonpath.find("$.users[?@.score > 85]", data):
    print(node.value)

# {'name': 'Sue', 'score': 100}
# {'name': 'John', 'score': 86, 'admin': True}

Or, reading JSON data from a file:

import json
import jsonpath_rfc9535 as jsonpath

with open("/path/to/some.json", encoding="utf-8") as fd:
    data = json.load(fd)

nodes = jsonpath.find("$.some.query", data)
values = nodes.values()
# ...

You could read data from a YAML formatted file too. If you have PyYaml installed:

import jsonpath_rfc9535 as jsonpath
import yaml

with open("some.yaml") as fd:
    data = yaml.safe_load(fd)

products = jsonpath.find("$..products.*", data).values()
# ...
  • Python JSONPath - Another Python package implementing JSONPath, but with additional features and customization options.
  • JSON P3 - RFC 9535 implemented in TypeScript.

API

find

find(query: str, value: JSONValue) -> JSONPathNodeList

Apply JSONPath expression query to value. value should arbitrary, possible nested, Python dictionaries, lists, strings, integers, floats, Booleans or None, as you would get from json.load().

A list of JSONPathNode instances is returned, one node for each value matched by query. The returned list will be empty if there were no matches.

Each JSONPathNode has properties:

  • value - The JSON-like value associated with the node.
  • location - A tuple of property names and array/list indexes that were required to reach the node's value in the target JSON document.
  • parent (New in version 0.2.0) - The node's parent node, or None if the current node is the root.
import jsonpath_rfc9535 as jsonpath

data = {
    "users": [
        {"name": "Sue", "score": 100},
        {"name": "John", "score": 86, "admin": True},
        {"name": "Sally", "score": 84, "admin": False},
        {"name": "Jane", "score": 55},
    ],
    "moderator": "John",
}

nodes = jsonpath.find("$.users[?@.score > 85]", data)

for node in nodes:
    print(f"{node.value} at '{node.path()}'")

# {'name': 'Sue', 'score': 100} at '$['users'][0]'
# {'name': 'John', 'score': 86, 'admin': True} at '$['users'][1]'

JSONPathNode.path() returns the normalized path to the node in the target JSON document.

JSONPathNodeList is a subclass of list with some helper methods.

  • values() returns a list of values, one for each node.
  • items() returns a list of (normalized path, value) tuples.

New in version 0.2.0

Assigning to JSONPathNode.value will update the node's value and mutate source data. Beware,updating data after evaluating a query can invalidate existing child node paths.

# ... continued from above

node = jsonpath.find_one("$.users[@.name == 'John'].score")
if node:
    node.value = 999

print(data["users"][1])  # {'name': 'John', 'score': 999, 'admin': True}

find_one

find_one(query: str, value: JSONValue) -> Optional[JSONPathNode]

find_one() accepts the same arguments as find(), but returns the first available JSONPathNode, or None if there were no matches.

find_one() is equivalent to:

def find_one(query, value):
    try:
        return next(iter(jsonpath.finditer(query, value)))
    except StopIteration:
        return None

finditer

finditer(query: str, value: JSONValue) -> Iterable[JSONPathNode]

finditer() accepts the same arguments as find(), but returns an iterator over JSONPathNode instances rather than a list. This could be useful if you're expecting a large number of results that you don't want to load into memory all at once.

compile

compile(query: str) -> JSONPathQuery

find(query, value) is a convenience function for JSONPathEnvironment().compile(query).apply(value). Use compile(query) to obtain a JSONPathQuery instance which can be applied to difference JSON-like values repeatedly.

import jsonpath_rfc9535 as jsonpath

value = {
    "users": [
        {"name": "Sue", "score": 100},
        {"name": "John", "score": 86, "admin": True},
        {"name": "Sally", "score": 84, "admin": False},
        {"name": "Jane", "score": 55},
    ],
    "moderator": "John",
}

query = jsonpath.compile("$.users[?@.score > 85]")

for node in query.apply(value):
    print(f"{node.value} at '{node.path()}'")

# {'name': 'Sue', 'score': 100} at '$['users'][0]'
# {'name': 'John', 'score': 86, 'admin': True} at '$['users'][1]'

A JSONPathQuery has a finditer(value) method too, and find(value) is an alias for apply(value).

License

python-jsonpath-rfc9535 is distributed under the terms of the MIT license.

Metadata

Release files for jsonpath-rfc9535 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for jsonpath-rfc9535 1.0.1
File Size Uploaded
jsonpath_rfc9535-1.0.1.tar.gz 27.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for jsonpath-rfc9535 1.0.1
File Interpreter ABI Platform
jsonpath_rfc9535-1.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 63.8 kB

Release files / jsonpath_rfc9535-1.0.1.tar.gz

Download URL jsonpath_rfc9535-1.0.1.tar.gz
Size 27.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9cab85a93f7ad6b2b8d9f31d9cb4216207a000de4eecdc4ac6cdfe2a79784c79
BLAKE2b-256 checksum
How to use checksums
068de3891ee43c1828805a28f16d09a91fd1bd5b76a30fbc93d55cc3343a4a50
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release files / jsonpath_rfc9535-1.0.1-py3-none-any.whl

Download URL jsonpath_rfc9535-1.0.1-py3-none-any.whl
Size 36.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b1c2176532776fa1cd02d8e00efa1a0088d55f47bb5e54ff22875cdbccafcdbd
BLAKE2b-256 checksum
How to use checksums
8ab533a308488c101300265f83aac0e85d1344fe59a43cb72763b450efe8245d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Release history Release notifications | RSS feed

2.0.2

2 release files

2.0.1

2 release files

2.0.0

2 release files

This release

1.0.1 This release

2 release files

1.0.0

2 release files

0.2.0

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page