Skip to content

API Reference

jsonpath.JSONPathEnvironment

JSONPath configuration.

This class contains settings for path tokenization, parsing and resolution behavior, plus convenience methods for matching an unparsed path to some data.

Most applications will want to create a single JSONPathEnvironment, or use jsonpath.compile(), jsonpath.findall(), etc. from the package-level default environment.

Environment customization

Environment customization is achieved by subclassing JSONPathEnvironment and overriding class attributes and/or methods. Some of these customizations include:

  • Changing the root ($), self (@) or filter context (_) token with class attributes root_token, self_token and filter_context_token.
  • Registering a custom lexer or parser with the class attributes lexer_class or parser_class. lexer_class must be a subclass of Lexer and parser_class must be a subclass of Parser.
  • Setup built-in function extensions by overriding setup_function_extensions()
  • Hook in to mapping and sequence item getting by overriding getitem().
  • Change filter comparison operator behavior by overriding compare().
PARAMETER DESCRIPTION
filter_caching

If True, filter expressions will be cached where possible.

TYPE: bool DEFAULT: True

unicode_escape

If True, decode UTF-16 escape sequences found in JSONPath string literals.

TYPE: bool DEFAULT: True

well_typed

Control well-typedness checks on filter function expressions. If True (the default), JSONPath expressions are checked for well-typedness as compile time.

New in version 0.10.0

TYPE: bool DEFAULT: True

Class attributes

ATTRIBUTE DESCRIPTION
fake_root_token

The pattern used to select a "fake" root node, one level above the real root node.

TYPE: str

filter_context_token

The pattern used to select extra filter context data. Defaults to "_".

TYPE: str

intersection_token

The pattern used as the intersection operator. Defaults to "&".

TYPE: str

key_token

The pattern used to identify the current key or index when filtering a, mapping or sequence. Defaults to "#".

TYPE: str

keys_selector_token

The pattern used as the "keys" selector. Defaults to "~".

TYPE: str

lexer_class

The lexer to use when tokenizing path strings.

TYPE: Type[Lexer]

max_int_index

The maximum integer allowed when selecting array items by index. Defaults to (2**53) - 1.

TYPE: int

min_int_index

The minimum integer allowed when selecting array items by index. Defaults to -(2**53) + 1.

TYPE: int

parser_class

The parser to use when parsing tokens from the lexer.

TYPE: Type[Parser]

root_token

The pattern used to select the root node in a JSON document. Defaults to "$".

TYPE: str

self_token

The pattern used to select the current node in a JSON document. Defaults to "@"

TYPE: str

union_token

The pattern used as the union operator. Defaults to "|".

TYPE: str

filter_caching instance-attribute

filter_caching: bool = filter_caching

Enable or disable filter expression caching.

function_extensions instance-attribute

function_extensions: Dict[str, Callable[..., Any]] = {}

A list of function extensions available to filters.

lexer instance-attribute

lexer: Lexer = lexer_class(env=self)

The lexer bound to this environment.

parser instance-attribute

parser: Parser = parser_class(env=self)

The parser bound to this environment.

unicode_escape instance-attribute

unicode_escape: bool = unicode_escape

Enable or disable decoding of UTF-16 escape sequences found in JSONPath string literals.

well_typed instance-attribute

well_typed: bool = well_typed

Control well-typedness checks on filter function expressions.

check_well_typedness

check_well_typedness(
    token: Token,
    func: FilterFunction,
    args: List[FilterExpression],
) -> None

Check the well-typedness of a function's arguments at compile-time.

compare

compare(left: object, operator: str, right: object) -> bool

Object comparison within JSONPath filters.

Override this to customize filter expression comparison operator behavior.

PARAMETER DESCRIPTION
left

The left hand side of the comparison expression.

TYPE: object

operator

The comparison expression's operator.

TYPE: str

right

The right hand side of the comparison expression.

TYPE: object

RETURNS DESCRIPTION
bool

True if the comparison between left and right, with the

bool

given operator, is truthy. False otherwise.

compile

compile(path: str) -> Union[JSONPath, CompoundJSONPath]

Prepare a path string ready for repeated matching against different data.

PARAMETER DESCRIPTION
path

A JSONPath as a string.

TYPE: str

RETURNS DESCRIPTION
Union[JSONPath, CompoundJSONPath]

A JSONPath or CompoundJSONPath, ready to match against some data. Expect a CompoundJSONPath if the path string uses the union or intersection operators.

RAISES DESCRIPTION
JSONPathSyntaxError

If path is invalid.

JSONPathTypeError

If filter functions are given arguments of an unacceptable type.

findall

findall(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

Find all objects in data matching the JSONPath path.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
path

The JSONPath as a string.

TYPE: str

data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
List[object]

A list of matched objects. If there are no matches, the list will be empty.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

findall_async async

findall_async(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

An async version of findall().

finditer

finditer(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Iterable[JSONPathMatch]

Generate JSONPathMatch objects for each match of path in data.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
path

The JSONPath as a string.

TYPE: str

data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Iterable[JSONPathMatch]

An iterator yielding JSONPathMatch objects for each match.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

finditer_async async

finditer_async(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> AsyncIterable[JSONPathMatch]

An async version of finditer().

getitem

getitem(obj: Any, key: Any) -> Any

Sequence and mapping item getter used throughout JSONPath resolution.

The default implementation of getitem simply calls operators.getitem() from Python's standard library. Same as obj[key].

PARAMETER DESCRIPTION
obj

A mapping or sequence that might contain key.

TYPE: Any

key

A mapping key, sequence index or sequence slice.

TYPE: Any

getitem_async async

getitem_async(obj: Any, key: object) -> Any

An async sequence and mapping item getter.

is_truthy

is_truthy(obj: object) -> bool

Test for truthiness when evaluating JSONPath filter expressions.

In some cases, RFC 9535 requires us to test for existence rather than truthiness. So the default implementation returns True for empty collections and None. The special UNDEFINED object means that obj was missing, as opposed to an explicit None.

PARAMETER DESCRIPTION
obj

Any object.

TYPE: object

RETURNS DESCRIPTION
bool

True if the object exists and is not False or 0.

match

match(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Union[JSONPathMatch, None]

Return a JSONPathMatch instance for the first object found in data.

None is returned if there are no matches.

PARAMETER DESCRIPTION
path

The JSONPath as a string.

TYPE: str

data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Union[JSONPathMatch, None]

A JSONPathMatch object for the first match, or None if there were no matches.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

query

query(
    path: str,
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    filter_context: Optional[FilterContextVars] = None,
) -> Query

Return a Query iterator over matches found by applying path to data.

Query objects are iterable.

for match in jsonpath.query("$.foo..bar", data):
    ...

You can skip and limit results with Query.skip() and Query.limit().

matches = (
    jsonpath.query("$.foo..bar", data)
    .skip(5)
    .limit(10)
)

for match in matches
    ...

Query.tail() will get the last n results.

for match in jsonpath.query("$.foo..bar", data).tail(5):
    ...

Get values for each match using Query.values().

for obj in jsonpath.query("$.foo..bar", data).limit(5).values():
    ...
PARAMETER DESCRIPTION
path

The JSONPath as a string.

TYPE: str

data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Query

A query iterator.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

setup_function_extensions

setup_function_extensions() -> None

Initialize function extensions.

validate_function_extension_signature

validate_function_extension_signature(
    token: Token, args: List[Any]
) -> List[Any]

Compile-time validation of function extension arguments.

RFC 9535 requires us to reject paths that use filter functions with too many or too few arguments.

jsonpath.JSONPathMatch

A matched object with a concrete path.

ATTRIBUTE DESCRIPTION
children

Matched child nodes. This will only be populated after all children have been visited, usually by using findall() or list(finditer()).

TYPE: List[JSONPathMatch]

obj

The matched object.

TYPE: object

parent

The immediate parent to this match in the JSON document. If this is the root node, parent will be None.

TYPE: Optional[JSONPathMatch]

path

The canonical string representation of the path to this match.

TYPE: str

parts

The keys, indices and/or slices that make up the path to this match.

TYPE: Tuple[PathPart, ...]

root

A reference to the root node in the JSON document.

TYPE: Union[Sequence[Any], Mapping[str, Any]]

value property

value: object

Return the value associated with this match/node.

add_child

add_child(*children: JSONPathMatch) -> None

Append one or more children to this match.

filter_context

filter_context() -> FilterContextVars

Return filter context data for this match.

pointer

pointer() -> JSONPointer

Return a JSONPointer pointing to this match's path.

jsonpath.JSONPath

A compiled JSONPath ready to be applied to a JSON string or Python object.

PARAMETER DESCRIPTION
env

The JSONPathEnvironment this path is bound to.

TYPE: JSONPathEnvironment

selectors

An iterable of JSONPathSelector objects, as generated by a Parser.

TYPE: Iterable[JSONPathSelector]

fake_root

Indicates if target JSON values should be wrapped in a single- element array, so as to make the target root value selectable.

TYPE: bool DEFAULT: False

ATTRIBUTE DESCRIPTION
env

The JSONPathEnvironment this path is bound to.

selectors

The JSONPathSelector instances that make up this path.

empty

empty() -> bool

Return True if this path has no selectors.

findall

findall(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

Find all objects in data matching the given JSONPath path.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
List[object]

A list of matched objects. If there are no matches, the list will

List[object]

be empty.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

findall_async async

findall_async(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

An async version of findall().

finditer

finditer(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Iterable[JSONPathMatch]

Generate JSONPathMatch objects for each match.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Iterable[JSONPathMatch]

An iterator yielding JSONPathMatch objects for each match.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

finditer_async async

finditer_async(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> AsyncIterable[JSONPathMatch]

An async version of finditer().

match

match(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Union[JSONPathMatch, None]

Return a JSONPathMatch instance for the first object found in data.

None is returned if there are no matches.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Union[JSONPathMatch, None]

A JSONPathMatch object for the first match, or None if there were no matches.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

query

query(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Query

Return a Query iterator over matches found by applying this path to data.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Query

A query iterator.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

singular_query

singular_query() -> bool

Return True if this JSONPath query is a singular query.

jsonpath.CompoundJSONPath

Multiple JSONPaths combined.

findall

findall(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

Find all objects in data matching the given JSONPath path.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
List[object]

A list of matched objects. If there are no matches, the list will be empty.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

findall_async async

findall_async(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> List[object]

An async version of findall().

finditer

finditer(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Iterable[JSONPathMatch]

Generate JSONPathMatch objects for each match.

If data is a string or a file-like objects, it will be loaded using json.loads() and the default JSONDecoder.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Iterable[JSONPathMatch]

An iterator yielding JSONPathMatch objects for each match.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

finditer_async async

finditer_async(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> AsyncIterable[JSONPathMatch]

An async version of finditer().

intersection

intersection(path: JSONPath) -> CompoundJSONPath

Intersection of this path and another path.

match

match(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Union[JSONPathMatch, None]

Return a JSONPathMatch instance for the first object found in data.

None is returned if there are no matches.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Union[JSONPathMatch, None]

A JSONPathMatch object for the first match, or None if there were no matches.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

query

query(
    data: Union[
        str, IOBase, Sequence[Any], Mapping[str, Any]
    ],
    *,
    filter_context: Optional[FilterContextVars] = None
) -> Query

Return a Query iterator over matches found by applying this path to data.

PARAMETER DESCRIPTION
data

A JSON document or Python object implementing the Sequence or Mapping interfaces.

TYPE: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]

filter_context

Arbitrary data made available to filters using the filter context selector.

TYPE: Optional[FilterContextVars] DEFAULT: None

RETURNS DESCRIPTION
Query

A query iterator.

RAISES DESCRIPTION
JSONPathSyntaxError

If the path is invalid.

JSONPathTypeError

If a filter expression attempts to use types in an incompatible way.

union

union(path: JSONPath) -> CompoundJSONPath

Union of this path and another path.

jsonpath.Query

A fluent API for managing JSONPathMatch iterators.

Usually you'll want to use jsonpath.query() or JSONPathEnvironment.query() to create instances of Query rather than instantiating Query directly.

PARAMETER DESCRIPTION
it

A JSONPathMatch iterable, as you'd get from jsonpath.finditer() or JSONPathEnvironment.finditer().

TYPE: Iterable[JSONPathMatch]

New in version 1.1.0

drop

drop(n: int) -> Query

Skip up to n matches from the query iterator.

RAISES DESCRIPTION
ValueError

If n < 0.

first

first(n: int) -> Query

Limit the query iterator to at most the first n matches.

first() is an alias for limit().

RAISES DESCRIPTION
ValueError

If n < 0.

first_one

first_one() -> Optional[JSONPathMatch]

Return the first JSONPathMatch or None if there were no matches.

head

head(n: int) -> Query

Limit the query iterator to at most the first n matches.

head() is an alias for limit().

RAISES DESCRIPTION
ValueError

If n < 0.

items

items() -> Iterable[Tuple[str, object]]

Return an iterable of (path, object) tuples, one for each match.

last

last(n: int) -> Query

Drop up to the last n matches from the iterator.

last() is an alias for tail().

RAISES DESCRIPTION
ValueError

If n < 0.

last_one

last_one() -> Optional[JSONPathMatch]

Return the last JSONPathMatch or None if there were no matches.

limit

limit(n: int) -> Query

Limit the query iterator to at most n matches.

RAISES DESCRIPTION
ValueError

If n < 0.

locations

locations() -> Iterable[str]

Return an iterable of normalized paths, one for each match.

one

one() -> Optional[JSONPathMatch]

Return the first JSONPathMatch or None if there were no matches.

one() is an alias for first_one().

pointers

pointers() -> Iterable[JSONPointer]

Return an iterable of JSONPointers, one for each match.

select

select(
    *expressions: Union[str, JSONPath, CompoundJSONPath],
    projection: Projection = Projection.RELATIVE
) -> Iterable[object]

Query projection using relative JSONPaths.

PARAMETER DESCRIPTION
expressions

One or more JSONPath query expressions to select relative to each match in this query iterator.

TYPE: Union[str, JSONPath, CompoundJSONPath] DEFAULT: ()

projection

The style of projection used when selecting values. Can be one of Projection.RELATIVE, Projection.ROOT or Projection.FLAT. Defaults to Projection.RELATIVE.

TYPE: Projection DEFAULT: RELATIVE

RETURNS DESCRIPTION
Iterable[object]

An iterable of objects built from selecting expressions relative to each match from the current query.

New in version 1.2.0

skip

skip(n: int) -> Query

Skip up to n matches from the query iterator.

RAISES DESCRIPTION
ValueError

If n < 0.

tail

tail(n: int) -> Query

Drop matches up to the last n matches from the iterator.

RAISES DESCRIPTION
ValueError

If n < 0.

take

take(n: int) -> Query

Return a new query iterating over the next n matches.

It is safe to continue using this query after calling take.

tee

tee(n: int = 2) -> Tuple[Query, ...]

Return n independent queries by teeing this query's iterator.

It is not safe to use a Query instance after calling tee().

values

values() -> Iterable[object]

Return an iterable of objects associated with each match.

jsonpath.Projection

Bases: Enum

Projection style used by Query.select().

FLAT class-attribute instance-attribute

FLAT = auto()

All selections are appended to a new array/list, without arrays and objects on the path to the selected value.

RELATIVE class-attribute instance-attribute

RELATIVE = auto()

The default projection. Selections include parent arrays and objects relative to the JSONPathMatch.

ROOT class-attribute instance-attribute

ROOT = auto()

Selections include parent arrays and objects relative to the root JSON value.

jsonpath.function_extensions.FilterFunction

Bases: ABC

Base class for typed function extensions.

arg_types abstractmethod property

arg_types: List[ExpressionType]

Argument types expected by the filter function.

return_type abstractmethod property

return_type: ExpressionType

The type of the value returned by the filter function.

__call__ abstractmethod

__call__(*args: Any, **kwds: Any) -> Any

Called the filter function.

jsonpath.function_extensions.ExpressionType

Bases: Enum

The type of a filter function argument or return value.

jsonpath.JSONPointer

Identify a single, specific value in JSON-like data, as per RFC 6901.

PARAMETER DESCRIPTION
pointer

A string representation of a JSON Pointer.

TYPE: str

parts

The keys, indices and/or slices that make up a JSON Pointer. If given, it is assumed that the parts have already been parsed by the JSONPath parser. unicode_escape and uri_decode are ignored if parts is given.

TYPE: Tuple[Union[int, str], ...] DEFAULT: ()

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing the pointer.

TYPE: bool DEFAULT: True

uri_decode

If True, the pointer will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

ATTRIBUTE DESCRIPTION
keys_selector

The non-standard token used to target a mapping key or name.

TYPE: str

max_int_index

The maximum integer allowed when resolving array items by index. Defaults to (2**53) - 1.

TYPE: int

min_int_index

The minimum integer allowed when resolving array items by index. Defaults to -(2**53) + 1.

TYPE: int

__truediv__

__truediv__(other: object) -> JSONPointer

Join this pointer with other.

other is expected to be a JSON Pointer string, possibly without a leading slash. If other does have a leading slash, the previous pointer is ignored and a new JSONPath is returned from other.

other should not be a "Relative JSON Pointer".

exists

exists(
    data: Union[
        str, IOBase, Sequence[object], Mapping[str, object]
    ]
) -> bool

Return True if this pointer can be resolved against data.

Note that JSONPointer.resolve() can return legitimate falsy values that form part of the target JSON document. This method will return True if a falsy value is found.

PARAMETER DESCRIPTION
data

The target JSON "document" or equivalent Python objects.

TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]

RETURNS DESCRIPTION
bool

True if this pointer can be resolved against data, or False otherwise.

New in version 0.9.0

from_match classmethod

from_match(match: JSONPathMatch) -> JSONPointer

Return a JSON Pointer for the path from a JSONPathMatch instance.

from_parts classmethod

from_parts(
    parts: Iterable[Union[int, str]],
    *,
    unicode_escape: bool = True,
    uri_decode: bool = False
) -> JSONPointer

Build a JSON Pointer from parts.

PARAMETER DESCRIPTION
parts

The keys, indices and/or slices that make up a JSONPointer.

TYPE: Iterable[Union[int, str]]

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing the pointer.

TYPE: bool DEFAULT: True

uri_decode

If True, the pointer will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
JSONPointer

A new JSONPointer built from parts.

is_relative_to

is_relative_to(other: JSONPointer) -> bool

Return True if this pointer points to a child of other.

join

join(*parts: str) -> JSONPointer

Join this pointer with parts.

Each part is expected to be a JSON Pointer string, possibly without a leading slash. If a part does have a leading slash, the previous pointer is ignored and a new JSONPointer is created, and processing of remaining parts continues.

parent

parent() -> JSONPointer

Return this pointer's parent, as a new JSONPointer.

If this pointer points to the document root, self is returned.

New in version 0.9.0

resolve

resolve(
    data: Union[
        str, IOBase, Sequence[object], Mapping[str, object]
    ],
    *,
    default: object = UNDEFINED
) -> object

Resolve this pointer against data.

PARAMETER DESCRIPTION
data

The target JSON "document" or equivalent Python objects.

TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]

default

A default value to return if the pointer can't be resolved against the given data.

TYPE: object DEFAULT: UNDEFINED

RETURNS DESCRIPTION
object

The object in data pointed to by this pointer.

RAISES DESCRIPTION
JSONPointerIndexError

When attempting to access a sequence by an out of range index, unless a default is given.

JSONPointerKeyError

If any mapping object along the path does not contain a specified key, unless a default is given.

JSONPointerTypeError

When attempting to resolve a non-index string path part against a sequence, unless a default is given.

resolve_parent

resolve_parent(
    data: Union[
        str, IOBase, Sequence[object], Mapping[str, object]
    ]
) -> Tuple[
    Union[Sequence[object], Mapping[str, object], None],
    object,
]

Resolve this pointer against data, return the object and its parent.

PARAMETER DESCRIPTION
data

The target JSON "document" or equivalent Python objects.

TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]

RETURNS DESCRIPTION
Tuple[Union[Sequence[object], Mapping[str, object], None], object]

A (parent, object) tuple, where parent will be None if this pointer points to the root node in the document. If the parent exists but the last object does not, (parent, UNDEFINED) will be returned.

RAISES DESCRIPTION
JSONPointerIndexError

When attempting to access a sequence by an out of range index, unless using the special - index.

JSONPointerKeyError

If any mapping object along the path does not contain a specified key, unless it is the last part of the pointer.

JSONPointerTypeError

When attempting to resolve a non-index string path part against a sequence.

to

to(
    rel: Union[RelativeJSONPointer, str],
    *,
    unicode_escape: bool = True,
    uri_decode: bool = False
) -> JSONPointer

Return a new pointer relative to this pointer.

PARAMETER DESCRIPTION
rel

A RelativeJSONPointer or a string following "Relative JSON Pointer" syntax.

TYPE: Union[RelativeJSONPointer, str]

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing the pointer.

TYPE: bool DEFAULT: True

uri_decode

If True, the pointer will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

See https://www.ietf.org/id/draft-hha-relative-json-pointer-00.html

jsonpath.RelativeJSONPointer

A Relative JSON Pointer.

See https://www.ietf.org/id/draft-hha-relative-json-pointer-00.html

PARAMETER DESCRIPTION
rel

A string following Relative JSON Pointer syntax.

TYPE: str

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing the pointer.

TYPE: bool DEFAULT: True

uri_decode

If True, the pointer will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

to

to(
    pointer: Union[JSONPointer, str],
    *,
    unicode_escape: bool = True,
    uri_decode: bool = False
) -> JSONPointer

Return a new JSONPointer relative to pointer.

PARAMETER DESCRIPTION
pointer

A JSONPointer instance or a string following JSON Pointer syntax.

TYPE: Union[JSONPointer, str]

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing the pointer.

TYPE: bool DEFAULT: True

uri_decode

If True, the pointer will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

jsonpath.JSONPatch

Modify JSON-like data with JSON Patch.

RFC 6902 defines operations to manipulate a JSON document. JSONPatch supports parsing and applying standard JSON Patch formatted operations, and provides a Python builder API following the same semantics as RFC 6902.

PARAMETER DESCRIPTION
ops

A JSON Patch formatted document or equivalent Python objects.

TYPE: Union[str, IOBase, Iterable[Mapping[str, object]], None] DEFAULT: None

unicode_escape

If True, UTF-16 escape sequences will be decoded before parsing JSON pointers.

TYPE: bool DEFAULT: True

uri_decode

If True, JSON pointers will be unescaped using urllib before being parsed.

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
JSONPatchError

If ops is given and any of the provided operations is malformed.

add

add(path: Union[str, JSONPointer], value: object) -> Self

Append an add operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

value

The object to add.

TYPE: object

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

addap

addap(path: Union[str, JSONPointer], value: object) -> Self

Append an addap operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

value

The object to add.

TYPE: object

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

addne

addne(path: Union[str, JSONPointer], value: object) -> Self

Append an addne operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

value

The object to add.

TYPE: object

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

apply

apply(
    data: Union[
        str,
        IOBase,
        MutableSequence[object],
        MutableMapping[str, object],
    ]
) -> object

Apply all operations from this patch to data.

If data is a string or file-like object, it will be loaded with json.loads. Otherwise data should be a JSON-like data structure and will be modified in place.

When modifying data in place, we return modified data too. This is to allow for replacing data's root element, which is allowed by some patch operations.

PARAMETER DESCRIPTION
data

The target JSON "document" or equivalent Python objects.

TYPE: Union[str, IOBase, MutableSequence[object], MutableMapping[str, object]]

RETURNS DESCRIPTION
object

Modified input data.

RAISES DESCRIPTION
JSONPatchError

When a patch operation fails.

JSONPatchTestFailure

When a test operation does not pass. JSONPatchTestFailure is a subclass of JSONPatchError.

asdicts

asdicts() -> List[Dict[str, object]]

Return a list of this patch's operations as dictionaries.

copy

copy(
    from_: Union[str, JSONPointer],
    path: Union[str, JSONPointer],
) -> Self

Append a copy operation to this patch.

PARAMETER DESCRIPTION
from_

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

move

move(
    from_: Union[str, JSONPointer],
    path: Union[str, JSONPointer],
) -> Self

Append a move operation to this patch.

PARAMETER DESCRIPTION
from_

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

remove

remove(path: Union[str, JSONPointer]) -> Self

Append a remove operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

replace

replace(
    path: Union[str, JSONPointer], value: object
) -> Self

Append a replace operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

value

The object to add.

TYPE: object

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.

test

test(path: Union[str, JSONPointer], value: object) -> Self

Append a test operation to this patch.

PARAMETER DESCRIPTION
path

A string representation of a JSON Pointer, or one that has already been parsed.

TYPE: Union[str, JSONPointer]

value

The object to test.

TYPE: object

RETURNS DESCRIPTION
Self

This JSONPatch instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.