core – JSONPath Core

class jsonpath.core.And(target: Any)

Bases: jsonpath.core.Compare

And, a boolean operator.

class jsonpath.core.Array(idx: Optional[Union[int, jsonpath.core.Slice]] = None)

Bases: jsonpath.core.Expr

Represent the array data if combine with expr (e.g., Name, Root) as the next part.

Use an array index to get the item of the array.

>>> p = Root().Array(0); print(p.get_expression())
$[0]
>>> p.find([1, 2])
[1]

Also can use a Slice to get partial items of the array.

>>> p = Root().Array(Slice(0, 3, 2)); print(p.get_expression())
$[:3:2]
>>> p.find([1, 2, 3, 4])
[1, 3]

Accept None to get all items of the array.

>>> p = Root().Array(); print(p.get_expression())
$[*]
>>> p.find([1, 2, 3, 4])
[1, 2, 3, 4]
class jsonpath.core.Brace(expr: jsonpath.core.Expr)

Bases: jsonpath.core.Expr

Brace groups part of expression, uses sub-expression to find the target data, and wraps the found result as an array.

>>> p = Root().Array().Name("a"); print(p.get_expression())
$[*].a
>>> p.find([{"a": 1}])
[1]
>>> p = Brace(p); print(p.get_expression())
($[*].a)
>>> p.find([{"a": 1}])
[[1]]

It seems to be useless but makes chaining filtering become possible. The expressions like “$[@ < 100][@ >= 50]” can not perform chaining filtering. Because the Predicate (and Array) class always unpacks the found elements to avoid the found result looking like [[[[[[[…]]]]]]]. So the right way to do chaining filter is that it should use with Brace class.

>>> p = Brace(Root().Predicate(Self() < 100)).Predicate(Self() >= 50)
>>> print(p.get_expression())
($[@ < 100])[@ >= 50]
>>> p.find([100, 99, 50, 1])
[99, 50]

Generally, we will use And expresion do that. e.g. “$[@ < 100 and @ >= 50]”

>>> p = Brace(
...     Root().Array().Name("a")
... ).Predicate(Self() == 1)
>>> print(p.get_expression())
($[*].a)[@ = 1]
>>> p.find([{"a": 1}, {"a": 2}, {"a": 1}, {}])
[1, 1]
class jsonpath.core.Compare(target: Any)

Bases: jsonpath.core.Expr

Base class of comparison operators.

Compare value between the first result of an expression, and the first result of an expression or simple value.

>>> Root().Predicate(Self() == 1)
JSONPath('$[@ = 1]', '[@ = 1]')
>>> Root().Predicate(Self().Equal(1))
JSONPath('$[@ = 1]', '[@ = 1]')
>>> Root().Predicate(Self() <= 1)
JSONPath('$[@ <= 1]', '[@ <= 1]')
>>> (
...     Root()
...     .Name("data")
...     .Predicate(
...         Self() != Root().Name("target")
...     )
... )
JSONPath('$.data[@ != $.target]', '[@ != $.target]')
class jsonpath.core.Contains(expr: jsonpath.core.Expr, target: Any, *args: List[Any])

Bases: jsonpath.core.Function

Determine the first result of expression contains the target substring.

>>> p = Root().Predicate(Contains(Name("name"), "red"))
>>> print(p.get_expression())
$[contains(name, "red")]
>>> p.find([
...     {"name": "red book"},
...     {"name": "red pen"},
...     {"name": "green book"}
... ])
[{'name': 'red book'}, {'name': 'red pen'}]

Check the specific key in the dictionary.

>>> p = Root().Predicate(Contains(Self(), "a"))
>>> print(p.get_expression())
$[contains(@, "a")]
>>> p.find([{"a": 0}, {"a": 1}, {}, {"b": 1}])
[{'a': 0}, {'a': 1}]
class jsonpath.core.Equal(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.Expr

Bases: object

JSONPath executable Class.

abstract find(element: Any)List[Any]

Find target data by the JSONPath expression.

Parameters

element (Any) – Root data where target data found from

Returns

A list of target data

Return type

List[Any]

find_first(element: Any)Any

Find first target data by the JSONPath expression.

Parameters

element (Any) – Root data where target data found from

Returns

the first target data

Return type

Any

Raises

JSONPathFindError – Found nothing

find_iter(element: Any)Generator[Any, None, None]

Iterable find target data by the JSONPath expression.

Parameters

element (Any) – Root data where target data found from

Returns

the generator of target data list

Return type

Generator[Any, None, None]

get_expression()str

Get full JSONPath expression.

get_begin()jsonpath.core.Expr

Get the begin expr of the combined expr.

Returns

The begin expr of the combined expr.

Return type

jsonpath.core.Expr

get_next()Optional[jsonpath.core.Expr]

Get the next part of expr in the combined expr.

Returns

The next part of expr in the combined expr.

Return type

jsonpath.core.Expr

chain(next_expr: T)T

Chain the next part of expr as a combined expr.

Parameters

next_expr (jsonpath.core.Expr) – The next part of expr in the combined expr.

Returns

The next part of expr in the combined expr.

Return type

jsonpath.core.Expr

__getattr__(name: str)Callable[[], jsonpath.core.Expr]

Create combined expr in a serial of chain class creations like Root().Name(“*”).

Parameters

name (str) – The name of the next part expr in combined expr.

Returns

The function for creating the next part of the combined expr.

Return type

Callable[[…], Expr]

Raises

AttributeError – The name of Expr Component not found

class jsonpath.core.ExprMeta(name: str, bases: Tuple[type], attr_dict: Dict[str, Any])

Bases: type

JSONPath Expr Meta Class.

class jsonpath.core.GreaterEqual(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.GreaterThan(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.Key(*args: List[Any])

Bases: jsonpath.core.Function

Key function is used to get the field name from dictionary data.

>>> Root().Predicate(Key() == "a")
JSONPath('$[key() = "a"]', '[key() = "a"]')

Same as Root().Name("a").

Filter all values which field name contains "book".

>>> p = Root().Predicate(Contains(Key(), "book"))
>>> print(p.get_expression())
$[contains(key(), "book")]
>>> p.find({"book 1": 1, "picture 2": 2})
[1]
class jsonpath.core.LessEqual(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.LessThan(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.Name(name: Optional[str] = None)

Bases: jsonpath.core.Expr

Represent the data of the field name. Represent the data of all fields if not providing the field name.

Parameters

name (Optional[str]) – The field name of the data.

>>> p = Name("abc"); print(p.get_expression())
abc
>>> p.find({"abc": 1})
[1]
>>> p = Name(); print(p.get_expression())
*
>>> p.find({"a": 1, "b": 2})
[1, 2]
>>> p = Name("a").Name("b"); print(p.get_expression())
a.b
>>> p.find({"a": {"b": 1}})
[1]
class jsonpath.core.Not(expr: jsonpath.core.Expr, *args: List[Any])

Bases: jsonpath.core.Function

Not, a boolean operator.

>>> Root().Predicate(Not(Name("enable")))
JSONPath('$[not(enable)]', '[not(enable)]')
class jsonpath.core.NotEqual(target: Any)

Bases: jsonpath.core.Compare

class jsonpath.core.Or(target: Any)

Bases: jsonpath.core.Compare

Or, a boolean operator.

class jsonpath.core.Predicate(expr: Union[jsonpath.core.Compare, jsonpath.core.Expr])

Bases: jsonpath.core.Expr

Filter items from the array by expr(e.g., Compare) if combine with expr (e.g., Name, Root) as the next part. It is also able to process dictionary.

Accept comparison expr for filtering. See more in Compare.

>>> p = Root().Predicate(Name("a") == 1); print(p.get_expression())
$[a = 1]
>>> p.find([{"a": 1}, {"a": 2}, {}])
[{'a': 1}]
>>> p = Root().Predicate(Contains(Key(), "a")); print(p.get_expression())
$[contains(key(), "a")]
>>> p.find({"a": 1, "ab": 2, "c": 3})
[1, 2]

Or accept single expr for filtering.

>>> p = Root().Predicate(Name("a")); print(p.get_expression())
$[a]
>>> p.find([{"a": 0}, {"a": 1}, {}])
[{'a': 1}]
class jsonpath.core.Root

Bases: jsonpath.core.Expr

Represent the root of data.

>>> p = Root(); print(p.get_expression())
$
>>> p.find([1])
[[1]]
class jsonpath.core.Search(expr: jsonpath.core.Expr)

Bases: jsonpath.core.Expr

Recursively search target in data.

Parameters

expr (Expr) – The expr is used to search in data recursively.

>>> p = Root().Search(Name("a")); print(p.get_expression())
$..a
>>> p.find({"a":{"a": 0}})
[{'a': 0}, 0]
class jsonpath.core.Self

Bases: jsonpath.core.Expr

Represent each item of the array data.

>>> p = Root().Predicate(Self()==1); print(p.get_expression())
$[@ = 1]
>>> p.find([1, 2, 1])
[1, 1]
class jsonpath.core.Slice(start: Optional[Union[jsonpath.core.Expr, int]] = None, stop: Optional[Union[jsonpath.core.Expr, int]] = None, step: Optional[Union[jsonpath.core.Expr, int]] = None)

Bases: jsonpath.core.Expr

Use it with Array to get partial items from the array data. Work like the Python slice(range).

class jsonpath.core.Value(value: Union[int, float, str, typing_extensions.Literal[None], typing_extensions.Literal[True], typing_extensions.Literal[False]])

Bases: jsonpath.core.Expr

Represent the value in the expression.

It is used mainly to support parsing comparison expression which value is on the left.

>>> p = Value("boo"); print(p.get_expression())
"boo"
>>> p.find([])
['boo']
>>> print(Value(True).get_expression())
true
>>> print(Value(False).get_expression())
false
>>> print(Value(None).get_expression())
null
>>> print(Value(1).get_expression())
1
>>> print(Value(1.1).get_expression())
1.1
>>> print(Value(1).LessThan(Value(2)).get_expression())
1 < 2
exception jsonpath.core.JSONPathError

Bases: Exception

JSONPath Base Exception.

exception jsonpath.core.JSONPathSyntaxError(expr: str)

Bases: jsonpath.core.JSONPathError, SyntaxError

JSONPath expression syntax error.

Parameters

expr (str) – JSONPath expression

exception jsonpath.core.JSONPathUndefinedFunctionError

Bases: jsonpath.core.JSONPathError

Undefined Function in JSONPath expression error.

exception jsonpath.core.JSONPathFindError

Bases: jsonpath.core.JSONPathError

JSONPath executable object finds nothing.