diff --git a/advanced/index.html b/advanced/index.html index 9ee345b..a204ec4 100644 --- a/advanced/index.html +++ b/advanced/index.html @@ -836,7 +836,7 @@
Arbitrary variables can be made available to filter expressions using the filter_context argument to findall()
and finditer()
. filter_context should be a mapping of strings to JSON-like objects, like lists, dictionaries, strings and integers.
Filter context variables are selected using the filter context selector, which defaults to _
and has usage similar to $
and @
.
Filter context variables are selected using a filter query starting with the filter context identifier, which defaults to _
and has usage similar to $
and @
.
import jsonpath
data = {
@@ -1007,40 +1007,56 @@ Identifier Tokens
Logical Operator Tokens
-TODO:
+By default, we accept both Python and C-style logical operators in filter expressions. That is, not
and !
are equivalent, and
and &&
are equivalent and or
and ||
are equivalent. You can change this using class attributes on a Lexer
subclass and setting the lexer_class
attribute on a JSONPathEnvironment
.
+This example changes all three logical operators to strictly match the JSONPath spec.
+from jsonpath import JSONPathEnvironment
+from jsonpath import Lexer
+
+class MyLexer(Lexer):
+ logical_not_pattern = r"!"
+ logical_and_pattern = r"&&"
+ logical_or_pattern = r"\|\|"
+
+class MyJSONPathEnvironment(JSONPathEnvironment):
+ lexer_class = MyLexer
+
+env = MyJSONPathEnvironment()
+env.compile("$.foo[?@.a > 0 && @.b < 100]") # OK
+env.compile("$.foo[?@.a > 0 and @.b < 100]") # JSONPathSyntaxError
+
Keys Selector
The non-standard keys selector is used to retrieve the keys/properties from a JSON Object or Python mapping. It defaults to ~
and can be changed using the keys_selector_token
attribute on a JSONPathEnvironment
subclass.
This example changes the keys selector to *~
.
-from jsonpath import JSONPathEnvironment
-
-class MyJSONPathEnvironment(JSONPathEnvironment):
- keys_selector_token = "*~"
-
-data = {
- "users": [
- {"name": "Sue", "score": 100},
- {"name": "John", "score": 86},
- {"name": "Sally", "score": 84},
- {"name": "Jane", "score": 55},
- ],
- "limit": 100,
-}
-
-env = MyJSONPathEnvironment()
-print(env.findall("$.users[0].*~", data)) # ['name', 'score']
+from jsonpath import JSONPathEnvironment
+
+class MyJSONPathEnvironment(JSONPathEnvironment):
+ keys_selector_token = "*~"
+
+data = {
+ "users": [
+ {"name": "Sue", "score": 100},
+ {"name": "John", "score": 86},
+ {"name": "Sally", "score": 84},
+ {"name": "Jane", "score": 55},
+ ],
+ "limit": 100,
+}
+
+env = MyJSONPathEnvironment()
+print(env.findall("$.users[0].*~", data)) # ['name', 'score']
Array Index Limits
Python JSONPath limits the minimum and maximum JSON array or Python sequence indices (including slice steps) allowed in a JSONPath query. The default minimum allowed index is set to -(2**53) + 1
, and the maximum to (2**53) - 1
. When a limit is reached, a JSONPathIndexError
is raised.
You can change the minimum and maximum allowed indices using the min_int_index
and max_int_index
attributes on a JSONPathEnvironment
subclass.
-from jsonpath import JSONPathEnvironment
-
-class MyJSONPathEnvironment(JSONPathEnvironment):
- min_int_index = -100
- max_int_index = 100
-
-env = MyJSONPathEnvironment()
-query = env.compile("$.users[999]")
-# jsonpath.exceptions.JSONPathIndexError: index out of range, line 1, column 8
+from jsonpath import JSONPathEnvironment
+
+class MyJSONPathEnvironment(JSONPathEnvironment):
+ min_int_index = -100
+ max_int_index = 100
+
+env = MyJSONPathEnvironment()
+query = env.compile("$.users[999]")
+# jsonpath.exceptions.JSONPathIndexError: index out of range, line 1, column 8
Subclassing Lexer
TODO:
diff --git a/api/index.html b/api/index.html
index 71aaea2..041ca6c 100644
--- a/api/index.html
+++ b/api/index.html
@@ -1835,7 +1835,7 @@ Class attributes
TYPE:
- Type[Lexer]
+ Type[Lexer]
@@ -4425,8 +4425,8 @@
- abstractmethod
property
+ abstractmethod
@@ -4449,8 +4449,8 @@
- abstractmethod
property
+ abstractmethod
diff --git a/custom_api/index.html b/custom_api/index.html
index 86cd13c..5f72a12 100644
--- a/custom_api/index.html
+++ b/custom_api/index.html
@@ -577,10 +577,30 @@
-
- jsonpath.lex.Lexer
+
+ Lexer
+
+
+
+
@@ -721,10 +741,30 @@
-
- jsonpath.lex.Lexer
+
+ Lexer
+
+
+
+
@@ -891,7 +931,9 @@
-
+
handler: python
+
TODO:
-handler: python
+
Tokenize a JSONPath string.
+Some customization can be achieved by subclassing Lexer and setting
+class attributes. Then setting lexer_class
on a JSONPathEnvironment
.
ATTRIBUTE | +DESCRIPTION | +
---|---|
key_pattern |
+
+
+
+ The regular expression pattern used to match mapping +keys/properties. ++ + |
+
logical_not_pattern |
+
+
+
+ The regular expression pattern used to match
+logical negation tokens. By default, + + |
+
logical_and_pattern |
+
+
+
+ The regular expression pattern used to match
+logical and tokens. By default, + + |
+
logical_or_pattern |
+
+
+
+ The regular expression pattern used to match
+logical or tokens. By default, + + |
+
TODO:
TODO:
diff --git a/objects.inv b/objects.inv index e63dc7d..be721b1 100644 Binary files a/objects.inv and b/objects.inv differ diff --git a/search/search_index.json b/search/search_index.json index 89b3cda..14e70c8 100644 --- a/search/search_index.json +++ b/search/search_index.json @@ -1 +1 @@ -{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Python JSONPath","text":"JSONPath is a mini language for selecting objects from data formatted in JavaScript Object Notation, or equivalent Python objects, like dictionaries and lists.
Python JSONPath is a non-evaluating, read-only implementation of JSONPath, suitable for situations where JSONPath query authors are untrusted. We follow most of the IETF JSONPath draft. See Notable differences for a list of areas where we deviate from the standard.
Since version 0.8.0, we also include implementations of JSON Pointer (RFC 6901) and JSON Patch (RFC 6902), plus methods for converting a JSONPathMatch to a JSONPointer
.
Install Python JSONPath using pip:
pip install python-jsonpath\n
Or Pipenv:
pipenv install python-jsonpath\n
Or pipx
pipx install python-jsonpath\n
Or from conda-forge:
conda install -c conda-forge python-jsonpath\n
"},{"location":"#example","title":"Example","text":"import jsonpath\nexample_data = {\n\"categories\": [\n{\n\"name\": \"footwear\",\n\"products\": [\n{\n\"title\": \"Trainers\",\n\"description\": \"Fashionable trainers.\",\n\"price\": 89.99,\n},\n{\n\"title\": \"Barefoot Trainers\",\n\"description\": \"Running trainers.\",\n\"price\": 130.00,\n},\n],\n},\n{\n\"name\": \"headwear\",\n\"products\": [\n{\n\"title\": \"Cap\",\n\"description\": \"Baseball cap\",\n\"price\": 15.00,\n},\n{\n\"title\": \"Beanie\",\n\"description\": \"Winter running hat.\",\n\"price\": 9.00,\n},\n],\n},\n],\n\"price_cap\": 10,\n}\nproducts = jsonpath.findall(\"$..products.*\", example_data)\nprint(products)\n
Which results in a list of all products from all categories:
[\n{\n\"title\": \"Trainers\",\n\"description\": \"Fashionable trainers.\",\n\"price\": 89.99\n},\n{\n\"title\": \"Barefoot Trainers\",\n\"description\": \"Running trainers.\",\n\"price\": 130.0\n},\n{\n\"title\": \"Cap\",\n\"description\": \"Baseball cap\",\n\"price\": 15.0\n},\n{\n\"title\": \"Beanie\",\n\"description\": \"Winter running hat.\",\n\"price\": 9.0\n}\n]\n
Or, reading data from a JSON formatted file:
import jsonpath\nwith open(\"some.json\") as fd:\nproducts = jsonpath.findall(\"$..products.*\", fd)\nprint(products)\n
You could use Python JSONPath on data read from a YAML formatted file too, or any data format that can be loaded into dictionaries and lists. If you have PyYAML installed:
import jsonpath\nimport yaml\nwith open(\"some.yaml\") as fd:\ndata = yaml.safe_load(fd)\nproducts = jsonpath.findall(\"$..products.*\", data)\nprint(products)\n
"},{"location":"#next-steps","title":"Next Steps","text":"Have a read through the Quick Start and High Level API Reference, or the default JSONPath Syntax supported by Python JSONPath.
If you're interested in customizing JSONPath, take a look at Advanced Usage and the Low Level API Reference.
"},{"location":"advanced/","title":"Advanced Usage","text":""},{"location":"advanced/#filter-variables","title":"Filter Variables","text":"Arbitrary variables can be made available to filter expressions using the filter_context argument to findall()
and finditer()
. filter_context should be a mapping of strings to JSON-like objects, like lists, dictionaries, strings and integers.
Filter context variables are selected using the filter context selector, which defaults to _
and has usage similar to $
and @
.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nuser_names = jsonpath.findall(\n\"$.users[?@.score < _.limit].name\",\ndata,\nfilter_context={\"limit\": 100},\n)\n
"},{"location":"advanced/#function-extensions","title":"Function Extensions","text":"Add, remove or replace filter functions by updating the function_extensions
attribute of a JSONPathEnvironment
. It is a regular Python dictionary mapping filter function names to any callable, like a function or class with a __call__
method.
Section 2.4.1 of the IETF JSONPath Draft specification defines a type system for function expressions and requires that we check that filter expressions are well-typed. With that in mind, you are encouraged to implement custom filter functions by extending jsonpath.function_extensions.FilterFunction
, which forces you to be explicit about the types of arguments the function extension accepts and the type of its return value.
Info
FilterFunction
was new in Python JSONPath version 0.10.0. Prior to that we did not enforce function expression well-typedness. To use any arbitrary callable as a function extension - or if you don't want built-in filter functions to raise a JSONPathTypeError
for function expressions that are not well-typed - set well_typed
to False
when constructing a JSONPathEnvironment
.
As an example, we'll add a min()
filter function, which will return the minimum of a sequence of values. If any of the values are not comparable, we'll return the special undefined
value instead.
from typing import Iterable\nimport jsonpath\nfrom jsonpath.function_extensions import ExpressionType\nfrom jsonpath.function_extensions import FilterFunction\nclass MinFilterFunction(FilterFunction):\n\"\"\"A JSONPath function extension returning the minimum of a sequence.\"\"\"\narg_types = [ExpressionType.VALUE]\nreturn_type = ExpressionType.VALUE\ndef __call__(self, value: object) -> object:\nif not isinstance(value, Iterable):\nreturn jsonpath.UNDEFINED\ntry:\nreturn min(value)\nexcept TypeError:\nreturn jsonpath.UNDEFINED\nenv = jsonpath.JSONPathEnvironment()\nenv.function_extensions[\"min\"] = MinFilterFunction()\nexample_data = {\"foo\": [{\"bar\": [4, 5]}, {\"bar\": [1, 5]}]}\nprint(env.findall(\"$.foo[?min(@.bar) > 1]\", example_data))\n
Now, when we use env.finall()
, env.finditer()
or env.compile()
, our min
function will be available for use in filter expressions.
$..products[?@.price == min($..products.price)]\n
"},{"location":"advanced/#built-in-functions","title":"Built-in Functions","text":"The built-in functions can be removed from a JSONPathEnvironment
by deleting the entry from function_extensions
.
import jsonpath\nenv = jsonpath.JSONPathEnvironment()\ndel env.function_extensions[\"keys\"]\n
Or aliased with an additional entry.
import jsonpath\nenv = jsonpath.JSONPathEnvironment()\nenv.function_extensions[\"properties\"] = env.function_extensions[\"keys\"]\n
Alternatively, you could subclass JSONPathEnvironment
and override the setup_function_extensions
method.
from typing import Iterable\nimport jsonpath\nclass MyEnv(jsonpath.JSONPathEnvironment):\ndef setup_function_extensions(self) -> None:\nsuper().setup_function_extensions()\nself.function_extensions[\"properties\"] = self.function_extensions[\"keys\"]\nself.function_extensions[\"min\"] = min_filter\ndef min_filter(obj: object) -> object:\nif not isinstance(obj, Iterable):\nreturn jsonpath.UNDEFINED\ntry:\nreturn min(obj)\nexcept TypeError:\nreturn jsonpath.UNDEFINED\nenv = MyEnv()\n
"},{"location":"advanced/#compile-time-validation","title":"Compile Time Validation","text":"Calls to type-aware function extension are validated at JSONPath compile-time automatically. If well_typed
is set to False
or a custom function extension does not inherit from FilterFunction
, its arguments can be validated by implementing the function as a class with a __call__
method, and a validate
method. validate
will be called after parsing the function, giving you the opportunity to inspect its arguments and raise a JSONPathTypeError
should any arguments be unacceptable. If defined, validate
must take a reference to the current environment, an argument list and the token pointing to the start of the function call.
def validate(\nself,\nenv: JSONPathEnvironment,\nargs: List[FilterExpression],\ntoken: Token,\n) -> List[FilterExpression]:\n
It should return an argument list, either the same as the input argument list, or a modified version of it. See the implementation of the built-in match
function for an example.
Python JSONPath can be customized by subclassing JSONPathEnvironment
and overriding class attributes and/or methods. Then using findall()
, finditer()
and compile()
methods of that subclass.
The default identifier tokens, like $
and @
, can be changed by setting attributes a on JSONPathEnvironment
. This example sets the root token (default $
) to be ^
.
import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nroot_token = \"^\"\ndata = {\n\"users\": [\n{\"name\": \"Sue\", \"score\": 100},\n{\"name\": \"John\", \"score\": 86},\n{\"name\": \"Sally\", \"score\": 84},\n{\"name\": \"Jane\", \"score\": 55},\n],\n\"limit\": 100,\n}\nenv = MyJSONPathEnvironment()\nuser_names = env.findall(\n\"^.users[?@.score < ^.limit].name\",\ndata,\n)\n
This table shows all available identifier token attributes.
attribute default filter_context_token_
keys_token #
root_token $
self_token @
"},{"location":"advanced/#logical-operator-tokens","title":"Logical Operator Tokens","text":"TODO:
"},{"location":"advanced/#keys-selector","title":"Keys Selector","text":"The non-standard keys selector is used to retrieve the keys/properties from a JSON Object or Python mapping. It defaults to ~
and can be changed using the keys_selector_token
attribute on a JSONPathEnvironment
subclass.
This example changes the keys selector to *~
.
from jsonpath import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nkeys_selector_token = \"*~\"\ndata = {\n\"users\": [\n{\"name\": \"Sue\", \"score\": 100},\n{\"name\": \"John\", \"score\": 86},\n{\"name\": \"Sally\", \"score\": 84},\n{\"name\": \"Jane\", \"score\": 55},\n],\n\"limit\": 100,\n}\nenv = MyJSONPathEnvironment()\nprint(env.findall(\"$.users[0].*~\", data)) # ['name', 'score']\n
"},{"location":"advanced/#array-index-limits","title":"Array Index Limits","text":"Python JSONPath limits the minimum and maximum JSON array or Python sequence indices (including slice steps) allowed in a JSONPath query. The default minimum allowed index is set to -(2**53) + 1
, and the maximum to (2**53) - 1
. When a limit is reached, a JSONPathIndexError
is raised.
You can change the minimum and maximum allowed indices using the min_int_index
and max_int_index
attributes on a JSONPathEnvironment
subclass.
from jsonpath import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nmin_int_index = -100\nmax_int_index = 100\nenv = MyJSONPathEnvironment()\nquery = env.compile(\"$.users[999]\")\n# jsonpath.exceptions.JSONPathIndexError: index out of range, line 1, column 8\n
"},{"location":"advanced/#subclassing-lexer","title":"Subclassing Lexer","text":"TODO:
"},{"location":"advanced/#subclassing-parser","title":"Subclassing Parser","text":"TODO:
"},{"location":"advanced/#get-item","title":"Get Item","text":"TODO:
"},{"location":"advanced/#truthiness-and-existence","title":"Truthiness and Existence","text":"TODO:
"},{"location":"advanced/#filter-infix-expressions","title":"Filter Infix Expressions","text":"TODO:
"},{"location":"api/","title":"API Reference","text":""},{"location":"api/#jsonpath.JSONPathEnvironment","title":"jsonpath.JSONPathEnvironment","text":"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 is achieved by subclassing JSONPathEnvironment
and overriding class attributes and/or methods. Some of these customizations include:
$
), self (@
) or filter context (_
) token with class attributes root_token
, self_token
and filter_context_token
.lexer_class
or parser_class
. lexer_class
must be a subclass of Lexer
and parser_class
must be a subclass of Parser
.setup_function_extensions()
getitem()
.compare()
.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
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
instance-attribute
","text":"filter_caching: bool = filter_caching\n
Enable or disable filter expression caching.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.function_extensions","title":"function_extensionsinstance-attribute
","text":"function_extensions: Dict[str, Callable[..., Any]] = {}\n
A list of function extensions available to filters.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.lexer","title":"lexerinstance-attribute
","text":"lexer: Lexer = self.lexer_class(env=self)\n
The lexer bound to this environment.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.parser","title":"parserinstance-attribute
","text":"parser: Parser = self.parser_class(env=self)\n
The parser bound to this environment.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.unicode_escape","title":"unicode_escapeinstance-attribute
","text":"unicode_escape: bool = unicode_escape\n
Enable or disable decoding of UTF-16 escape sequences found in JSONPath string literals.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.well_typed","title":"well_typedinstance-attribute
","text":"well_typed: bool = well_typed\n
Control well-typedness checks on filter function expressions.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.check_well_typedness","title":"check_well_typedness","text":"check_well_typedness(\ntoken: Token,\nfunc: FilterFunction,\nargs: List[FilterExpression],\n) -> None\n
Check the well-typedness of a function's arguments at compile-time.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.compare","title":"compare","text":"compare(left: object, operator: str, right: object) -> bool\n
Object comparison within JSONPath filters.
Override this to customize filter expression comparison operator behavior.
PARAMETER DESCRIPTIONleft
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
bool
True
if the comparison between left and right, with the
bool
given operator, is truthy. False
otherwise.
compile(path: str) -> Union[JSONPath, CompoundJSONPath]\n
Prepare a path string ready for repeated matching against different data.
PARAMETER DESCRIPTIONpath
A JSONPath as a string.
TYPE: str
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.
JSONPathSyntaxError
If path is invalid.
JSONPathTypeError
If filter functions are given arguments of an unacceptable type.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.findall","title":"findall","text":"findall(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.findall_async","title":"findall_asyncasync
","text":"findall_async(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
getitem(obj: Any, key: Any) -> Any\n
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]
.
obj
A mapping or sequence that might contain key.
TYPE: Any
key
A mapping key, sequence index or sequence slice.
TYPE: Any
async
","text":"getitem_async(obj: Any, key: object) -> Any\n
An async sequence and mapping item getter.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.is_truthy","title":"is_truthy","text":"is_truthy(obj: object) -> bool\n
Test for truthiness when evaluating JSONPath filter expressions.
In some cases, the IETF JSONPath draft 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
.
obj
Any object.
TYPE: object
bool
True
if the object exists and is not False
or 0
.
match(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.setup_function_extensions","title":"setup_function_extensions","text":"setup_function_extensions() -> None\n
Initialize function extensions.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.validate_function_extension_signature","title":"validate_function_extension_signature","text":"validate_function_extension_signature(\ntoken: Token, args: List[Any]\n) -> List[Any]\n
Compile-time validation of function extension arguments.
The IETF JSONPath draft requires us to reject paths that use filter functions with too many or too few arguments.
"},{"location":"api/#jsonpath.JSONPathMatch","title":"jsonpath.JSONPathMatch","text":"A matched object with a concrete path.
ATTRIBUTE DESCRIPTIONchildren
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]]
add_child(*children: JSONPathMatch) -> None\n
Append one or more children to this match.
"},{"location":"api/#jsonpath.match.JSONPathMatch.filter_context","title":"filter_context","text":"filter_context() -> FilterContextVars\n
Return filter context data for this match.
"},{"location":"api/#jsonpath.match.JSONPathMatch.pointer","title":"pointer","text":"pointer() -> JSONPointer\n
Return a JSONPointer
pointing to this match's path.
A compiled JSONPath ready to be applied to a JSON string or Python object.
PARAMETER DESCRIPTIONenv
The JSONPathEnvironment
this path is bound to.
TYPE: JSONPathEnvironment
selectors
An iterable of JSONPathSelector
objects, as generated by a Parser
.
TYPE: Iterable[JSONPathSelector]
env
The JSONPathEnvironment
this path is bound to.
selectors
The JSONPathSelector
instances that make up this path.
"},{"location":"api/#jsonpath.path.JSONPath.empty","title":"empty","text":"
empty() -> bool\n
Return True
if this path has no selectors.
findall(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will
List[object]
be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.findall_async","title":"findall_asyncasync
","text":"findall_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
match(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.singular_query","title":"singular_query","text":"singular_query() -> bool\n
Return True
if this JSONPath query is a singular query.
Multiple JSONPath
s combined.
findall(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.findall_async","title":"findall_asyncasync
","text":"findall_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
intersection(path: JSONPath) -> CompoundJSONPath\n
Intersection of this path and another path.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.match","title":"match","text":"match(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.union","title":"union","text":"union(path: JSONPath) -> CompoundJSONPath\n
Union of this path and another path.
"},{"location":"api/#jsonpath.function_extensions.FilterFunction","title":"jsonpath.function_extensions.FilterFunction","text":" Bases: ABC
Base class for typed function extensions.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.arg_types","title":"arg_typesabstractmethod
property
","text":"arg_types: List[ExpressionType]\n
Argument types expected by the filter function.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.return_type","title":"return_typeabstractmethod
property
","text":"return_type: ExpressionType\n
The type of the value returned by the filter function.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.__call__","title":"__call__abstractmethod
","text":"__call__(*args: Any, **kwds: Any) -> Any\n
Called the filter function.
"},{"location":"api/#jsonpath.function_extensions.ExpressionType","title":"jsonpath.function_extensions.ExpressionType","text":" Bases: Enum
The type of a filter function argument or return value.
"},{"location":"api/#jsonpath.JSONPointer","title":"jsonpath.JSONPointer","text":"Identify a single, specific value in JSON-like data, as per RFC 6901.
PARAMETER DESCRIPTIONpointer
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
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__(other: object) -> JSONPointer\n
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\".
"},{"location":"api/#jsonpath.pointer.JSONPointer.exists","title":"exists","text":"exists(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n]\n) -> bool\n
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.
data
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]
bool
True if this pointer can be resolved against data, or False otherwise.
New in version 0.9.0
"},{"location":"api/#jsonpath.pointer.JSONPointer.from_match","title":"from_matchclassmethod
","text":"from_match(match: JSONPathMatch) -> JSONPointer\n
Return a JSON Pointer for the path from a JSONPathMatch instance.
"},{"location":"api/#jsonpath.pointer.JSONPointer.from_parts","title":"from_partsclassmethod
","text":"from_parts(\nparts: Iterable[Union[int, str]],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Build a JSON Pointer from parts.
PARAMETER DESCRIPTIONparts
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
JSONPointer
A new JSONPointer
built from parts.
is_relative_to(other: JSONPointer) -> bool\n
Return True if this pointer points to a child of other.
"},{"location":"api/#jsonpath.pointer.JSONPointer.join","title":"join","text":"join(*parts: str) -> JSONPointer\n
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() -> JSONPointer\n
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
"},{"location":"api/#jsonpath.pointer.JSONPointer.resolve","title":"resolve","text":"resolve(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n],\n*,\ndefault: object = UNDEFINED\n) -> object\n
Resolve this pointer against data.
PARAMETER DESCRIPTIONdata
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
object
The object in data pointed to by this pointer.
RAISES DESCRIPTIONJSONPointerIndexError
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.
"},{"location":"api/#jsonpath.pointer.JSONPointer.resolve_parent","title":"resolve_parent","text":"resolve_parent(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n]\n) -> Tuple[\nUnion[Sequence[object], Mapping[str, object], None],\nobject,\n]\n
Resolve this pointer against data, return the object and its parent.
PARAMETER DESCRIPTIONdata
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]
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.
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.
"},{"location":"api/#jsonpath.pointer.JSONPointer.to","title":"to","text":"to(\nrel: Union[RelativeJSONPointer, str],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Return a new pointer relative to this pointer.
PARAMETER DESCRIPTIONrel
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
"},{"location":"api/#jsonpath.RelativeJSONPointer","title":"jsonpath.RelativeJSONPointer","text":"A Relative JSON Pointer.
See https://www.ietf.org/id/draft-hha-relative-json-pointer-00.html
PARAMETER DESCRIPTIONrel
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(\npointer: Union[JSONPointer, str],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Return a new JSONPointer relative to pointer.
PARAMETER DESCRIPTIONpointer
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
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.
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
JSONPatchError
If ops is given and any of the provided operations is malformed.
"},{"location":"api/#jsonpath.patch.JSONPatch.add","title":"add","text":"add(path: Union[str, JSONPointer], value: object) -> Self\n
Append an add operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
apply(\ndata: Union[\nstr,\nIOBase,\nMutableSequence[object],\nMutableMapping[str, object],\n]\n) -> object\n
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 DESCRIPTIONdata
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, MutableSequence[object], MutableMapping[str, object]]
object
Modified input data.
RAISES DESCRIPTIONJSONPatchError
When a patch operation fails.
JSONPatchTestFailure
When a test operation does not pass. JSONPatchTestFailure
is a subclass of JSONPatchError
.
asdicts() -> List[Dict[str, object]]\n
Return a list of this patch's operations as dictionaries.
"},{"location":"api/#jsonpath.patch.JSONPatch.copy","title":"copy","text":"copy(\nfrom_: Union[str, JSONPointer],\npath: Union[str, JSONPointer],\n) -> Self\n
Append a copy operation to this patch.
PARAMETER DESCRIPTIONfrom_
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]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
move(\nfrom_: Union[str, JSONPointer],\npath: Union[str, JSONPointer],\n) -> Self\n
Append a move operation to this patch.
PARAMETER DESCRIPTIONfrom_
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]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
remove(path: Union[str, JSONPointer]) -> Self\n
Append a remove operation to this patch.
PARAMETER DESCRIPTIONpath
A string representation of a JSON Pointer, or one that has already been parsed.
TYPE: Union[str, JSONPointer]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
replace(\npath: Union[str, JSONPointer], value: object\n) -> Self\n
Append a replace operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
test(path: Union[str, JSONPointer], value: object) -> Self\n
Append a test operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
Largely motivated by its integration with Python Liquid, Python JSONPath offers an asynchronous API that allows for items in a target data structure to be \"fetched\" lazily.
findall_async()
and finditer_async()
are asyncio equivalents to findall()
and finditer()
. By default, any class implementing the mapping or sequence interfaces, and a __getitem_async__()
method, will have __getitem_async__()
awaited instead of calling __getitem__()
when resolving mapping keys or sequence indices.
In this example, showing a lazy-loading collections of Player
objects, only the \"A\" team's players are fetched from the database, and only when they are first accessed.
from collections import abc\nfrom dataclasses import dataclass\nfrom typing import Dict\nfrom typing import Iterator\nfrom typing import List\nimport jsonpath\n@dataclass\nclass Player:\nname: str\npid: int\nrank: int\nclass LazyPlayers(abc.Mapping[str, Player]):\ndef __init__(self, names: List[str]):\nself.names = names\nself.cached_players: Dict[str, Player] = {}\ndef __len__(self) -> int:\nreturn len(self.names)\ndef __iter__(self) -> Iterator[str]:\nreturn iter(self.names)\ndef __getitem__(self, k: str) -> Player:\nif self.cached_players is None:\n# Blocking IO here\nself.cached_players = get_stuff_from_database()\nreturn self.cached_players[k]\nasync def __getitem_async__(self, k: str) -> Player:\nif self.cached_players is None:\n# Do async IO here.\nself.cached_players = await get_stuff_from_database_async()\nreturn self.cached_players[k]\ndata = {\n\"teams\": {\n\"A Team\": LazyPlayers([\"Sue\", \"Bob\"]),\n\"B Team\": LazyPlayers([\"Sally\", \"Frank\"]),\n}\n}\nbest_a_team_players = jsonpath.findall_async(\"$.teams['A Team'][?rank >= 8]\", data)\n
"},{"location":"async/#custom-async-item-getting","title":"Custom Async Item Getting","text":"TODO:
"},{"location":"cli/","title":"Command Line Interface","text":"New in version 0.9.0
Python JSONPath includes a script called json
, exposing JSONPath, JSON Pointer and JSON Patch features on the command line. Use the --version
argument to check the current version of Python JSONPath, and the --help
argument to display command information.
$ json --version\npython-jsonpath, version 0.9.0\n
$ json --help\nusage: json [-h] [--debug] [--pretty] [-v] [--no-unicode-escape] COMMAND ...\nJSONPath, JSON Pointer and JSON Patch utilities.\npositional arguments:\n COMMAND\n path Find objects in a JSON document given a JSONPath.\n pointer Resolve a JSON Pointer against a JSON document.\n patch Apply a JSON Patch to a JSON document.\noptional arguments:\n -h, --help show this help message and exit\n --debug Show stack traces. (default: False)\n --pretty Add indents and newlines to output JSON. (default: False)\n -v, --version Show the version and exit.\n --no-unicode-escape Disable decoding of UTF-16 escape sequence within paths and pointers. (default:\n False)\nUse [json COMMAND --help] for command specific help.\nUsage Examples:\n Find objects in source.json matching a JSONPath, write them to result.json.\n $ json path -q \"$.foo['bar'][?@.baz > 1]\" -f source.json -o result.json\n\n Resolve a JSON Pointer against source.json, pretty print the result to stdout.\n $ json --pretty pointer -p \"/foo/bar/0\" -f source.json\n\n Apply JSON Patch patch.json to JSON from stdin, output to result.json.\n $ cat source.json | json patch /path/to/patch.json -o result.json\n
Use json COMMAND --help
for command specific help.
$ json path --help\nusage: json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT]\nFind objects in a JSON document given a JSONPath.\noptional arguments:\n -h, --help show this help message and exit\n -q QUERY, --query QUERY\n JSONPath query string.\n -r PATH_FILE, --path-file PATH_FILE\n Text file containing a JSONPath query.\n -f FILE, --file FILE File to read the target JSON document from. Defaults to reading from the\n standard input stream.\n -o OUTPUT, --output OUTPUT\n File to write resulting objects to, as a JSON array. Defaults to the standard\n output stream.\n --no-type-checks Disables filter expression well-typedness checks.\n
"},{"location":"cli/#global-options","title":"Global Options","text":"These arguments apply to any subcommand and must be listed before the command.
"},{"location":"cli/#-debug","title":"--debug
","text":"Enable debugging. Display full stack traces, if available, when errors occur. Without the --debug
option, the following example shows a short \"json path syntax error\" message.
$ json path -q \"$.1\" -f /tmp/source.json\njson path syntax error: unexpected token '1', line 1, column 2\n
With the --debug
option, we get the stack trace triggered by JSONPathSyntaxError
.
$ json --debug path -q \"$.1\" -f /tmp/source.json\nTraceback (most recent call last):\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/bin/json\", line 8, in <module>\n sys.exit(main())\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py\", line 338, in main\n args.func(args)\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py\", line 234, in handle_path_command\n path = jsonpath.compile(args.query or args.path_file.read())\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/env.py\", line 148, in compile\n _path: Union[JSONPath, CompoundJSONPath] = JSONPath(\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/path.py\", line 49, in __init__\n self.selectors = tuple(selectors)\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/parse.py\", line 256, in parse\n raise JSONPathSyntaxError(\njsonpath.exceptions.JSONPathSyntaxError: unexpected token '1', line 1, column 2\n
"},{"location":"cli/#-pretty","title":"--pretty
","text":"Enable pretty formatting when outputting JSON. Adds newlines and indentation to output specified with the -o
or --output
option. Without the --pretty
option, the following example output is on one line.
$ json pointer -p \"/categories/1/products/0\" -f /tmp/source.json\n{\"title\": \"Cap\", \"description\": \"Baseball cap\", \"price\": 15.0}\n
With the --pretty
option, we get nicely formatted JSON output.
$ json --pretty pointer -p \"/categories/1/products/0\" -f /tmp/source.json\n{\n \"title\": \"Cap\",\n \"description\": \"Baseball cap\",\n \"price\": 15.0\n}\n
"},{"location":"cli/#-no-unicode-escape","title":"--no-unicode-escape
","text":"Disable decoding of UTF-16 escape sequences, including surrogate paris. This can improve performance if you know your paths and pointers don't contain UTF-16 escape sequences.
$ json --no-unicode-escape path -q \"$.price_cap\" -f /tmp/source.json\n
"},{"location":"cli/#commands","title":"Commands","text":"One of the subcommands path
, pointer
or patch
must be specified, depending on whether you want to search a JSON document with a JSONPath, resolve a JSON Pointer against a JSON document or apply a JSON Patch to a JSON Document.
path
","text":"Find objects in a JSON document given a JSONPath. One of -q
/--query
or -r
/--path-file
must be given. -q
being a JSONPath given on the command line as a string, -r
being the path to a file containing a JSONPath.
json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT]\n
"},{"location":"cli/#-q-query","title":"-q
/ --query
","text":"The JSONPath as a string.
$ json path -q \"$.price_cap\" -f /tmp/source.json\n
$ json path --query \"$.price_cap\" -f /tmp/source.json\n
"},{"location":"cli/#-r-path-file","title":"-r
/ --path-file
","text":"The path to a file containing a JSONPath.
$ json path -r /tmp/path.txt -f /tmp/source.json\n
$ json path --path-file /tmp/path.txt -f /tmp/source.json\n
"},{"location":"cli/#-f-file","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json path -q \"$.price_cap\" -f /tmp/source.json\n
$ json path -q \"$.price_cap\" --file /tmp/source.json\n
"},{"location":"cli/#-o-output","title":"-o
/ --output
","text":"The path to a file to write resulting objects to, as a JSON array. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json path -q \"$.price_cap\" -f /tmp/source.json -o result.json\n
$ json path -q \"$.price_cap\" -f /tmp/source.json --output result.json\n
"},{"location":"cli/#-no-type-checks","title":"--no-type-checks
","text":"New in version 0.10.0
Disables JSONPath filter expression well-typedness checks. The well-typedness of a filter expression is defined by the IETF JSONPath Draft specification.
"},{"location":"cli/#pointer","title":"pointer
","text":"Resolve a JSON Pointer against a JSON document. One of -p
/--pointer
or -r
/--pointer-file
must be given. -p
being a JSON Pointer given on the command line as a string, -r
being the path to a file containing a JSON Pointer.
json pointer [-h] (-p POINTER | -r POINTER_FILE) [-f FILE] [-o OUTPUT] [-u]\n
"},{"location":"cli/#-p-pointer","title":"-p
/ --pointer
","text":"An RFC 6901 formatted JSON Pointer string.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json\n
$ json pointer --pointer \"/categories/0/name\" -f /tmp/source.json\n
"},{"location":"cli/#-r-pointer-file","title":"-r
/ --pointer-file
","text":"The path to a file containing a JSON Pointer.
$ json pointer -r /tmp/pointer.txt -f /tmp/source.json\n
$ json pointer --pointer-file /tmp/pointer.txt -f /tmp/source.json\n
"},{"location":"cli/#-f-file_1","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json\n
$ json pointer -p \"/categories/0/name\" --file /tmp/source.json\n
"},{"location":"cli/#-o-output_1","title":"-o
/ --output
","text":"The path to a file to write the resulting object to. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json -o result.json\n
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json --output result.json\n
"},{"location":"cli/#-u-uri-decode","title":"-u
/ --uri-decode
","text":"Enable URI decoding of the JSON Pointer. In this example, we would look for a property called \"hello world\" in the root of the target document.
$ json pointer -p \"/hello%20world\" -f /tmp/source.json -u\n
$ json pointer -p \"/hello%20world\" -f /tmp/source.json --uri-decode\n
"},{"location":"cli/#patch","title":"patch
","text":"Apply a JSON Patch to a JSON document. Unlike path
and pointer
commands, a patch can't be given as a string argument. PATCH
is a positional argument that should be a file path to a JSON Patch document or a hyphen (-
), which means the patch document will be read from the standard input stream.
json patch [-h] [-f FILE] [-o OUTPUT] [-u] PATCH\n
These examples read the patch from patch.json
and the document to modify from target.json
$ json patch /tmp/patch.json -f /tmp/target.json\n
$ cat /tmp/patch.json | json patch - -f /tmp/target.json\n
"},{"location":"cli/#-f-file_2","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json patch /tmp/patch.json -f /tmp/target.json\n
$ json patch /tmp/patch.json --file /tmp/target.json\n
"},{"location":"cli/#-o-output_2","title":"-o
/ --output
","text":"The path to a file to write the resulting object to. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json patch /tmp/patch.json -f /tmp/target.json -o result.json\n
$ json patch /tmp/patch.json -f /tmp/target.json --output result.json\n
"},{"location":"cli/#-u-uri-decode_1","title":"-u
/ --uri-decode
","text":"Enable URI decoding of JSON Pointers in the patch document.
$ json patch /tmp/patch.json -f /tmp/target.json -u\n
$ json patch /tmp/patch.json -f /tmp/target.json --uri-decode\n
"},{"location":"custom_api/","title":"Low Level API Reference","text":""},{"location":"custom_api/#jsonpath.token.Token","title":"jsonpath.token.Token","text":"A token, as returned from lex.Lexer.tokenize()
.
kind
The token's type. It is always one of the constants defined in jsonpath.token.py.
TYPE: str
value
The path substring containing text for the token.
TYPE: str
index
The index at which value starts in path.
TYPE: str
path
A reference to the complete JSONPath string from which this token derives.
TYPE: str
position() -> Tuple[int, int]\n
Return the line and column number for the start of this token.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression","title":"jsonpath.filter.FilterExpression","text":" Bases: ABC
Base class for all filter expression nodes.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.children","title":"childrenabstractmethod
","text":"children() -> List[FilterExpression]\n
Return a list of direct child expressions.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.evaluate","title":"evaluateabstractmethod
","text":"evaluate(context: FilterContext) -> object\n
Resolve the filter expression in the given context.
PARAMETER DESCRIPTIONcontext
Contextual information the expression might choose use during evaluation.
TYPE: FilterContext
object
The result of evaluating the expression.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.evaluate_async","title":"evaluate_asyncasync
abstractmethod
","text":"evaluate_async(context: FilterContext) -> object\n
An async version of evaluate
.
abstractmethod
","text":"set_children(children: List[FilterExpression]) -> None\n
Update this expression's child expressions.
children is assumed to have the same number of items as is returned by self.children, and in the same order.
"},{"location":"custom_api/#jsonpathlexlexer","title":"jsonpath.lex.Lexer","text":"TODO:
"},{"location":"custom_api/#jsonpathparseparser","title":"jsonpath.parse.Parser","text":"TODO:
"},{"location":"custom_api/#jsonpathselectorsjsonpathselector","title":"jsonpath.selectors.JSONPathSelector","text":"TODO:
"},{"location":"custom_api/#jsonpathstreamtokenstream","title":"jsonpath.stream.TokenStream","text":"TODO:
"},{"location":"exceptions/","title":"Exceptions","text":"Each of the following exceptions has a token
property, referencing the Token
that caused the error. You can use Token.position()
to get the token's line and column number.
Bases: Exception
Base exception for all errors.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Optional[Token]
DEFAULT: None
Bases: JSONPathError
An exception raised when parsing a JSONPath string.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
Bases: JSONPathError
An exception raised due to a type error.
This should only occur at when evaluating filter expressions.
"},{"location":"exceptions/#jsonpath.JSONPathIndexError","title":"jsonpath.JSONPathIndexError","text":" Bases: JSONPathError
An exception raised when an array index is out of range.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
Bases: JSONPathError
An exception raised when an unknown function extension is called.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
A filter function is a named function that can be called as part of a filter selector expression. Here we describe built-in filters. You can define your own function extensions too.
"},{"location":"functions/#count","title":"count()
","text":"count(obj: object) -> Optional[int]\n
Return the number of items in obj. If the object does not respond to Python's len()
function, None
is returned.
$.categories[?count(@.products.*) >= 2]\n
"},{"location":"functions/#isinstance","title":"isinstance()
","text":"New in version 0.6.0
isinstance(obj: object, t: str) -> bool\n
Return True
if the type of obj matches t. This function allows t to be one of several aliases for the real Python \"type\". Some of these aliases follow JavaScript/JSON semantics.
For example :
$.categories[?isinstance(@.length, 'number')]\n
And is()
is an alias for isinstance()
:
$.categories[?is(@.length, 'number')]\n
"},{"location":"functions/#length","title":"length()
","text":"length(obj: object) -> Optional[int]\n
Return the number of items in the input object. If the object does not respond to Python's len()
function, None
is returned.
$.categories[?length(@) > 1]\n
"},{"location":"functions/#match","title":"match()
","text":"match(obj: object, pattern: str) -> bool\n
Return True
if obj is a string and is a full match to the regex pattern.
$..products[?match(@.title, \".+ainers.+\")]\n
If pattern is a string literal, it will be compiled at compile time, and raise a JSONPathTypeError
at compile time if it's invalid.
If pattern is a query and the result is not a valid regex, False
is returned.
search()
","text":"search(obj: object, pattern: str) -> bool\n
Return True
if obj is a string and it contains the regexp pattern.
$..products[?search(@.title, \"ainers\")]\n
If pattern is a string literal, it will be compiled at compile time, and raise a JSONPathTypeError
at compile time if it's invalid.
If pattern is a query and the result is not a valid regex, False
is returned.
typeof()
","text":"New in version 0.6.0
typeof(obj: object) -> str\n
Return the type of obj as a string. The strings returned from this function use JavaScript/JSON terminology like \"string\", \"array\" and \"object\", much like the result of JavaScript's typeof
operator.
$.categories[?typeof(@.length) == 'number']\n
type()
is and alias for typeof()
.
jsonpath.function_extensions.TypeOf
takes a single_number_type
argument, which controls the behavior of typeof()
when given and int or float. By default, single_number_type
is True
and \"number\"
is returned. Register a new instance of TypeOf
with a JSONPathEnvironment
with single_number_type
set to False
and \"int\"
and \"float\"
will be returned when given integers and floats, respectively.
single_number_type
is False
float \"number\" or \"float\" if single_number_type
is False
"},{"location":"functions/#value","title":"value()
","text":"value(nodes: object) -> object | undefined\n
Return the first value from nodes resulting from a JSONPath query, if there is only one node, or undefined
otherwise.
$..products[?value(@.price) == 9]\n
"},{"location":"pointers/","title":"JSON Pointers","text":"New in version 0.8.0
JSON Pointer (RFC 6901) is a string syntax for targeting a single value (JSON object, array or scalar) in a JSON document. Whereas a JSONPath has the potential to yield many values from a JSON document, a JSON Pointer can resolve to at most one value.
JSON Pointers are a fundamental part of JSON Patch (RFC 6902). Each patch operation must have at least one pointer, identifying the target value.
Note
We have extended RFC 6901 to handle our non-standard JSONPath keys selector and index/property pointers from Relative JSON Pointer.
"},{"location":"pointers/#resolvedata","title":"resolve(data)
","text":"Resolve this pointer against data. data can be a file-like object or string containing JSON formatted data, or a Python Mapping
or Sequence
, like a dictionary or list.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.resolve(example_data)) # 1\n
"},{"location":"pointers/#resolve_parentdata","title":"resolve_parent(data)
","text":"Resolve this pointer against data, return the object and its parent as a (parent, object)
tuple.
If object does not exist in data but parent does, (parent, UNDEFINED)
will be returned. Where jsonpath.pointer.UNDEFINED
indicates the lack of a value.
If this pointer points to the JSON document root, parent will be None
.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.resolve_parent(example_data)) # ([1, 2, 3], 1)\n# 'thing' does not exist\npointer = JSONPointer(\"/foo/thing\")\nprint(pointer.resolve_parent(example_data)) # ({'bar': [1, 2, 3]}, <jsonpath.pointer._Undefined object at 0x7f0c7cf77040>)\npointer = JSONPointer(\"\")\nprint(pointer.resolve_parent(example_data)) # (None, {'foo': {'bar': [1, 2, 3]}})\n
"},{"location":"pointers/#existsdata","title":"exists(data)
","text":"New in version 0.9.0
Return True if this pointer can be resolved against data, or False otherwise. 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.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}, \"baz\": False}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.exists(example_data)) # True\npointer = JSONPointer(\"/foo/bar/9\")\nprint(pointer.exists(example_data)) # False\npointer = JSONPointer(\"/baz\")\nprint(pointer.exists(example_data)) # True\n
"},{"location":"pointers/#joinparts","title":"join(*parts)
","text":"New in version 0.9.0
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.
join()
is equivalent to using the slash (/
) operator for each argument.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nprint(pointer) # /foo/bar\nprint(pointer.join(\"baz\")) # /foo/bar/baz\nprint(pointer.join(\"baz\", \"0\")) # /foo/bar/baz/0\n
"},{"location":"pointers/#parent","title":"parent()
","text":"New in version 0.9.0
Return this pointer's parent as a new JSONPointer
. If this pointer points to the document root, self is returned.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nprint(pointer) # /foo/bar\nprint(pointer.parent()) # /foo\n
"},{"location":"pointers/#is_relative_topointer","title":"is_relative_to(pointer)
","text":"Return True if this pointer points to a child of the argument pointer, which must be a JSONPointer
instance.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nanother_pointer = JSONPointer(\"/foo/bar/0\")\nprint(another_pointer.is_relative_to(pointer)) # True\nanother_pointer = JSONPointer(\"/foo/baz\")\nprint(another_pointer.is_relative_to(pointer)) # False\n
"},{"location":"pointers/#torel","title":"to(rel)
","text":"New in version 0.9.0
Return a new JSONPointer
relative to this pointer. rel should be a RelativeJSONPointer
instance or a string following Relative JSON Pointer syntax.
from jsonpath import JSONPointer\ndata = {\"foo\": {\"bar\": [1, 2, 3], \"baz\": [4, 5, 6]}}\npointer = JSONPointer(\"/foo/bar/2\")\nprint(pointer.resolve(data)) # 3\nprint(pointer.to(\"0-1\").resolve(data)) # 2\nprint(pointer.to(\"2/baz/2\").resolve(data)) # 6\n
A RelativeJSONPointer
can be instantiated for repeated application to multiple different pointers.
from jsonpath import JSONPointer\nfrom jsonpath import RelativeJSONPointer\ndata = {\"foo\": {\"bar\": [1, 2, 3], \"baz\": [4, 5, 6], \"some\": \"thing\"}}\nsome_pointer = JSONPointer(\"/foo/bar/0\")\nanother_pointer = JSONPointer(\"/foo/baz/2\")\nrel = RelativeJSONPointer(\"2/some\")\nprint(rel.to(some_pointer).resolve(data)) # thing\nprint(rel.to(another_pointer).resolve(data)) # thing\n
"},{"location":"pointers/#slash-operator","title":"Slash Operator","text":"New in version 0.9.0
The slash operator allows you to create pointers that are children of an existing pointer.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/users\")\nchild_pointer = pointer / \"score\" / \"0\"\nanother_child_pointer = pointer / \"score/1\"\nprint(child_pointer) # \"/users/score/0\"\nprint(another_child_pointer) # \"/users/score/1\"\n
"},{"location":"quickstart/","title":"Quick Start","text":"This page gets you started using JSONPath, JSON Pointer and JSON Patch wih Python. See JSONPath Syntax for information on JSONPath selector syntax.
"},{"location":"quickstart/#findallpath-data","title":"findall(path, data)
","text":"Find all objects matching a JSONPath with jsonpath.findall()
. It takes, as arguments, a JSONPath string and some data object. It always returns a list of objects selected from data, never a scalar value.
data can be a file-like object or string containing JSON formatted data, or a Python Mapping
or Sequence
, like a dictionary or list. In this example we select user names from a dictionary containing a list of user dictionaries.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nuser_names = jsonpath.findall(\"$.users.*.name\", data)\n
Where user_names
is now equal to:
[\"Sue\", \"John\", \"Sally\", \"Jane\"]\n
If the same data were in a file called users.json
, we might use findall()
like this:
import jsonpath\nwith open(\"users.json\") as fd:\nuser_names = jsonpath.findall(\"$.users.*.name\", fd)\n
"},{"location":"quickstart/#finditerpath-data","title":"finditer(path, data)
","text":"Use jsonpath.finditer()
to iterate over instances of jsonpath.JSONPathMatch
for every object in data that matches path. It accepts the same arguments as findall()
, a path string and data from which to select matches.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nmatches = jsonpath.finditer(\"$.users.*.name\", data)\nfor match in matches:\nprint(matches)\n
The string representation of a JSONPathMatch
shows the matched object and the canonical path to that object.
'Sue' @ $['users'][0]['name']\n'John' @ $['users'][1]['name']\n'Sally' @ $['users'][2]['name']\n'Jane' @ $['users'][3]['name']\n
The selected object is available from a JSONPathMatch
as obj
and its path, as a string, as path
. Other useful properties of JSONPathMatch
include a reference to the parent match, a list of child matches, and a parts
tuple of keys and indices that make up the path.
compile(path)
","text":"When you have a JSONPath that needs to be matched against different data repeatedly, you can compile the path ahead of time using jsonpath.compile()
. It takes a path as a string and returns a JSONPath
instance. JSONPath
has findall()
and finditer()
methods that behave similarly to package-level findall()
and finditer()
, just without the path
argument.
import jsonpath\nsome_data = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n]\n}\nother_data = {\n\"users\": [\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\npath = jsonpath.compile(\"$.users.*.name\")\nsome_users = path.findall(some_data)\nother_users = path.findall(other_data)\n
"},{"location":"quickstart/#matchpath-data","title":"match(path, data)
","text":"New in version 0.8.0
Get a jsonpath.JSONPathMatch
instance for the first match found in data. If there are no matches, None
is returned. match()
accepts the same arguments as findall()
.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nmatch = jsonpath.match(\"$.users[?@.score > 85].name\", data)\nif match:\nprint(match) # 'Sue' @ $['users'][0]['name']\nprint(match.obj) # Sue\n
"},{"location":"quickstart/#pointerresolvepointer-data","title":"pointer.resolve(pointer, data)
","text":"New in version 0.8.0
Resolve a JSON Pointer (RFC 6901) against some data. A JSON Pointer references a single object on a specific \"path\" in a JSON document. Here, pointer can be a string representation of a JSON Pointer or a list of parts that make up a pointer. data can be a file-like object or string containing JSON formatted data, or equivalent Python objects.
from jsonpath import pointer\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nsue_score = pointer.resolve(\"/users/0/score\", data)\nprint(sue_score) # 100\njane_score = pointer.resolve([\"users\", 3, \"score\"], data)\nprint(jane_score) # 55\n
If the pointer can't be resolved against the target JSON document - due to missing keys/properties or out of range indices - a JSONPointerIndexError
, JSONPointerKeyError
or JSONPointerTypeError
will be raised, each of which inherit from JSONPointerResolutionError
. A default value can be given, which will be returned in the event of a JSONPointerResolutionError
.
from jsonpath import pointer\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n]\n}\nsue_score = pointer.resolve(\"/users/99/score\", data, default=0)\nprint(sue_score) # 0\n
See also JSONPathMatch.pointer()
, which builds a JSONPointer
from a JSONPathMatch
.
patch.apply(patch, data)
","text":"New in version 0.8.0
Apply a JSON Patch (RFC 6902) to some data. A JSON Patch defines update operation to perform on a JSON document.
patch can be a string or file-like object containing a valid JSON Patch document, or an iterable of dictionaries.
data is the target JSON document to modify. 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.
from jsonpath import patch\npatch_operations = [\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"foo\": {}}},\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"bar\": []}},\n{\"op\": \"copy\", \"from\": \"/some/other\", \"path\": \"/some/foo/else\"},\n{\"op\": \"add\", \"path\": \"/some/foo/bar/-\", \"value\": 1},\n]\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(patch_operations, data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
Use the JSONPatch class to create a patch for repeated application.
from jsonpath import JSONPatch\npatch = JSONPatch(\n[\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"foo\": {}}},\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"bar\": []}},\n{\"op\": \"copy\", \"from\": \"/some/other\", \"path\": \"/some/foo/else\"},\n{\"op\": \"add\", \"path\": \"/some/foo/bar/-\", \"value\": 1},\n]\n)\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
JSONPatch also offers a builder API for constructing JSON patch documents. We use strings as JSON Pointers in this example, but existing JSONPointer instances are OK too.
from jsonpath import JSONPatch\npatch = (\nJSONPatch()\n.add(\"/some/foo\", {\"foo\": []})\n.add(\"/some/foo\", {\"bar\": []})\n.copy(\"/some/other\", \"/some/foo/else\")\n.add(\"/some/foo/bar/-\", \"/some/foo/else\")\n)\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
"},{"location":"quickstart/#whats-next","title":"What's Next?","text":"Read about user-defined filter functions at Function Extensions, or see how to make extra data available to filters with Extra Filter Context.
findall()
, finditer()
and compile()
are shortcuts that use the defaultJSONPathEnvironment
. jsonpath.findall(path, data)
is equivalent to:
jsonpath.JSONPathEnvironment().compile(path).findall(data)\n
If you would like to customize Python JSONPath, see Advanced Usage.
"},{"location":"syntax/","title":"JSONPath Syntax","text":"Python JSONPath's default syntax is an opinionated combination of JSONPath features from existing, popular implementations, and much of the IETF JSONPath draft. If you're already familiar with JSONPath syntax, skip to notable differences.
Imagine a JSON document as a tree structure, where each object (mapping) and array can contain more objects, arrays and scalar values. Every object, array and scalar value is a node in the tree, and the outermost object or array is the \"root\" node.
For our purposes, a JSON \"document\" could be a file containing valid JSON data, a Python string containing valid JSON data, or a Python Object
made up of dictionaries (or any Mapping), lists (or any Sequence), strings, etc.
We chain selectors together to retrieve nodes from the target document. Each selector operates on the nodes matched by preceding selectors. What follows is a description of those selectors.
"},{"location":"syntax/#selectors","title":"Selectors","text":""},{"location":"syntax/#root","title":"Root ($
)","text":"$
refers to the first node in the target document, be it an object or an array. Unless referencing the root node from inside a filter expression, $
is optional. The following two examples are equivalent.
$.categories.*.name\n
categories.*.name\n
An empty path or a path containing just the root ($
) selector returns the input data in its entirety.
.thing
, [thing]
or ['thing']
)","text":"Select nodes by property/key name using dot notation (.something
) or bracket notation ([something]
). If a target property/key contains reserved characters, it must use bracket notation and be enclosed in quotes (['thing']
).
A dot in front of bracket notation is OK, but unnecessary. The following examples are equivalent.
$.categories[0].name\n
$.categories[0][name]\n
$.categories[0]['name']\n
"},{"location":"syntax/#array-indices-0-or-1","title":"Array indices ([0]
or [-1]
)","text":"Select an item from an array by its index. Indices are zero-based and enclosed in brackets. If the index is negative, items are selected from the end of the array. Considering example data from the top of this page, the following examples are equivalent.
$.categories[0]\n
$.categories[-1]\n
"},{"location":"syntax/#wildcard-or","title":"Wildcard (.*
or [*]
)","text":"Select all elements from an array or all values from an object using *
. These two examples are equivalent.
$.categories[0].products.*\n
$.categories[0].products[*]\n
"},{"location":"syntax/#keys-or","title":"Keys (.~
or [~]
)","text":"New in version 0.6.0
Select keys/properties from an object using ~
.
$.categories.~\n
$.categories[~]\n
"},{"location":"syntax/#slices-0-1-or-10-1","title":"Slices ([0:-1]
or [-1:0:-1]
)","text":"Select a range of elements from an array using slice notation. The start index, stop index and step are all optional. These examples are equivalent.
$.categories[0:]\n
$.categories[0:-1:]\n
$.categories[0:-1:1]\n
$.categories[::]\n
"},{"location":"syntax/#lists-1-2-1020","title":"Lists ([1, 2, 10:20]
)","text":"Select multiple indices, slices or properties using list notation (sometimes known as a \"union\" or \"segment\", we use \"union\" to mean something else).
$..products.*.[title, price]\n
"},{"location":"syntax/#recursive-descent","title":"Recursive descent (..
)","text":"The ..
selector visits every node beneath the current selection. If a property selector, using dot notation, follows ..
, the dot is optional. These two examples are equivalent.
$..title\n
$...title\n
"},{"location":"syntax/#filters-expression","title":"Filters ([?EXPRESSION]
)","text":"Filters allow you to remove nodes from a selection using a Boolean expression. When filtering a mapping-like object, #
references the current key/property and @
references the current value associated with #
. When filtering a sequence-like object, @
references the current item and #
will hold the item's index in the sequence.
$..products[?(@.price < $.price_cap)]\n
$..products[?@.price < $.price_cap]\n
Comparison operators include ==
, !=
, <
, >
, <=
and >=
. Plus <>
as an alias for !=
.
in
and contains
are membership operators. left in right
is equivalent to right contains left
.
&&
and ||
are logical operators, and
and or
work too.
=~
matches the left value with a regular expression literal. Regular expressions use a syntax similar to that found in JavaScript, where the pattern to match is surrounded by slashes, optionally followed by flags.
$..products[?(@.description =~ /.*trainers/i)]\n
Filter expressions can call predefined function extensions too.
$.categories[?count(@.products.*) >= 2]\n
undefined
can be used to filter on the absence of a key/property or an undefined value returned from a filter function. missing
is an alias for undefined
.
$..products[?@.sale_price == undefined]\n
"},{"location":"syntax/#union-and-intersection","title":"Union (|
) and intersection (&
)","text":"Union (|
) and intersection (&
) are similar to Python's set operations, but we don't dedupe the matches (matches will often contain unhashable objects).
The |
operator combines matches from two or more paths. This example selects a single list of all prices, plus the price cap as the last element.
$..products.*.price | $.price_cap\n
The &
operator produces matches that are common to both left and right paths. This example would select the list of products that are common to both the \"footwear\" and \"headwear\" categories.
$.categories[?(@.name == 'footwear')].products.* & $.categories[?(@.name == 'headwear')].products.*\n
Note that |
and &
are not allowed inside filter expressions.
This is a list of things that you might find in other JSONPath implementation that we don't support (yet).
selector.func()
.jsonpath.findall()
, never a scalar value.JSONPathMatch
instances to JSONPointer
s, and a JSONPatch
builder API for modifying JSON-like data structures using said pointers.And this is a list of areas where we deviate from the IETF JSONPath draft.
$
) is optional and paths starting with a dot (.
) are OK. .thing
is the same as $.thing
, as is thing
, $[thing]
and $[\"thing\"]
.match()
and search()
filter functions use Python's standard library re
module, which, at least, doesn't support Unicode properties. We might add an implementation of match()
and search()
using the third party regex package in the future.$..
is equivalent to $..*
.undefined
as well as implicit existence tests.1.
is equivalent to 1.0
.And this is a list of features that are uncommon or unique to Python JSONPath.
in
and contains
, plus list/array literals.|
is a union operator, where matches from two or more JSONPaths are combined. This is not part of the Python API, but built-in to the JSONPath syntax.&
is an intersection operator, where we exclude matches that don't exist in both left and right paths. This is not part of the Python API, but built-in to the JSONPath syntax.#
is the current key/property or index identifier when filtering a mapping or sequence._
is a filter context selector. With usage similar to $
and @
, _
exposes arbitrary data from the filter_context
argument to findall()
and finditer()
.~
is a \"keys\" or \"properties\" selector.JSONPath is a mini language for selecting objects from data formatted in JavaScript Object Notation, or equivalent Python objects, like dictionaries and lists.
Python JSONPath is a non-evaluating, read-only implementation of JSONPath, suitable for situations where JSONPath query authors are untrusted. We follow most of the IETF JSONPath draft. See Notable differences for a list of areas where we deviate from the standard.
Since version 0.8.0, we also include implementations of JSON Pointer (RFC 6901) and JSON Patch (RFC 6902), plus methods for converting a JSONPathMatch to a JSONPointer
.
Install Python JSONPath using pip:
pip install python-jsonpath\n
Or Pipenv:
pipenv install python-jsonpath\n
Or pipx
pipx install python-jsonpath\n
Or from conda-forge:
conda install -c conda-forge python-jsonpath\n
"},{"location":"#example","title":"Example","text":"import jsonpath\nexample_data = {\n\"categories\": [\n{\n\"name\": \"footwear\",\n\"products\": [\n{\n\"title\": \"Trainers\",\n\"description\": \"Fashionable trainers.\",\n\"price\": 89.99,\n},\n{\n\"title\": \"Barefoot Trainers\",\n\"description\": \"Running trainers.\",\n\"price\": 130.00,\n},\n],\n},\n{\n\"name\": \"headwear\",\n\"products\": [\n{\n\"title\": \"Cap\",\n\"description\": \"Baseball cap\",\n\"price\": 15.00,\n},\n{\n\"title\": \"Beanie\",\n\"description\": \"Winter running hat.\",\n\"price\": 9.00,\n},\n],\n},\n],\n\"price_cap\": 10,\n}\nproducts = jsonpath.findall(\"$..products.*\", example_data)\nprint(products)\n
Which results in a list of all products from all categories:
[\n{\n\"title\": \"Trainers\",\n\"description\": \"Fashionable trainers.\",\n\"price\": 89.99\n},\n{\n\"title\": \"Barefoot Trainers\",\n\"description\": \"Running trainers.\",\n\"price\": 130.0\n},\n{\n\"title\": \"Cap\",\n\"description\": \"Baseball cap\",\n\"price\": 15.0\n},\n{\n\"title\": \"Beanie\",\n\"description\": \"Winter running hat.\",\n\"price\": 9.0\n}\n]\n
Or, reading data from a JSON formatted file:
import jsonpath\nwith open(\"some.json\") as fd:\nproducts = jsonpath.findall(\"$..products.*\", fd)\nprint(products)\n
You could use Python JSONPath on data read from a YAML formatted file too, or any data format that can be loaded into dictionaries and lists. If you have PyYAML installed:
import jsonpath\nimport yaml\nwith open(\"some.yaml\") as fd:\ndata = yaml.safe_load(fd)\nproducts = jsonpath.findall(\"$..products.*\", data)\nprint(products)\n
"},{"location":"#next-steps","title":"Next Steps","text":"Have a read through the Quick Start and High Level API Reference, or the default JSONPath Syntax supported by Python JSONPath.
If you're interested in customizing JSONPath, take a look at Advanced Usage and the Low Level API Reference.
"},{"location":"advanced/","title":"Advanced Usage","text":""},{"location":"advanced/#filter-variables","title":"Filter Variables","text":"Arbitrary variables can be made available to filter expressions using the filter_context argument to findall()
and finditer()
. filter_context should be a mapping of strings to JSON-like objects, like lists, dictionaries, strings and integers.
Filter context variables are selected using a filter query starting with the filter context identifier, which defaults to _
and has usage similar to $
and @
.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nuser_names = jsonpath.findall(\n\"$.users[?@.score < _.limit].name\",\ndata,\nfilter_context={\"limit\": 100},\n)\n
"},{"location":"advanced/#function-extensions","title":"Function Extensions","text":"Add, remove or replace filter functions by updating the function_extensions
attribute of a JSONPathEnvironment
. It is a regular Python dictionary mapping filter function names to any callable, like a function or class with a __call__
method.
Section 2.4.1 of the IETF JSONPath Draft specification defines a type system for function expressions and requires that we check that filter expressions are well-typed. With that in mind, you are encouraged to implement custom filter functions by extending jsonpath.function_extensions.FilterFunction
, which forces you to be explicit about the types of arguments the function extension accepts and the type of its return value.
Info
FilterFunction
was new in Python JSONPath version 0.10.0. Prior to that we did not enforce function expression well-typedness. To use any arbitrary callable as a function extension - or if you don't want built-in filter functions to raise a JSONPathTypeError
for function expressions that are not well-typed - set well_typed
to False
when constructing a JSONPathEnvironment
.
As an example, we'll add a min()
filter function, which will return the minimum of a sequence of values. If any of the values are not comparable, we'll return the special undefined
value instead.
from typing import Iterable\nimport jsonpath\nfrom jsonpath.function_extensions import ExpressionType\nfrom jsonpath.function_extensions import FilterFunction\nclass MinFilterFunction(FilterFunction):\n\"\"\"A JSONPath function extension returning the minimum of a sequence.\"\"\"\narg_types = [ExpressionType.VALUE]\nreturn_type = ExpressionType.VALUE\ndef __call__(self, value: object) -> object:\nif not isinstance(value, Iterable):\nreturn jsonpath.UNDEFINED\ntry:\nreturn min(value)\nexcept TypeError:\nreturn jsonpath.UNDEFINED\nenv = jsonpath.JSONPathEnvironment()\nenv.function_extensions[\"min\"] = MinFilterFunction()\nexample_data = {\"foo\": [{\"bar\": [4, 5]}, {\"bar\": [1, 5]}]}\nprint(env.findall(\"$.foo[?min(@.bar) > 1]\", example_data))\n
Now, when we use env.finall()
, env.finditer()
or env.compile()
, our min
function will be available for use in filter expressions.
$..products[?@.price == min($..products.price)]\n
"},{"location":"advanced/#built-in-functions","title":"Built-in Functions","text":"The built-in functions can be removed from a JSONPathEnvironment
by deleting the entry from function_extensions
.
import jsonpath\nenv = jsonpath.JSONPathEnvironment()\ndel env.function_extensions[\"keys\"]\n
Or aliased with an additional entry.
import jsonpath\nenv = jsonpath.JSONPathEnvironment()\nenv.function_extensions[\"properties\"] = env.function_extensions[\"keys\"]\n
Alternatively, you could subclass JSONPathEnvironment
and override the setup_function_extensions
method.
from typing import Iterable\nimport jsonpath\nclass MyEnv(jsonpath.JSONPathEnvironment):\ndef setup_function_extensions(self) -> None:\nsuper().setup_function_extensions()\nself.function_extensions[\"properties\"] = self.function_extensions[\"keys\"]\nself.function_extensions[\"min\"] = min_filter\ndef min_filter(obj: object) -> object:\nif not isinstance(obj, Iterable):\nreturn jsonpath.UNDEFINED\ntry:\nreturn min(obj)\nexcept TypeError:\nreturn jsonpath.UNDEFINED\nenv = MyEnv()\n
"},{"location":"advanced/#compile-time-validation","title":"Compile Time Validation","text":"Calls to type-aware function extension are validated at JSONPath compile-time automatically. If well_typed
is set to False
or a custom function extension does not inherit from FilterFunction
, its arguments can be validated by implementing the function as a class with a __call__
method, and a validate
method. validate
will be called after parsing the function, giving you the opportunity to inspect its arguments and raise a JSONPathTypeError
should any arguments be unacceptable. If defined, validate
must take a reference to the current environment, an argument list and the token pointing to the start of the function call.
def validate(\nself,\nenv: JSONPathEnvironment,\nargs: List[FilterExpression],\ntoken: Token,\n) -> List[FilterExpression]:\n
It should return an argument list, either the same as the input argument list, or a modified version of it. See the implementation of the built-in match
function for an example.
Python JSONPath can be customized by subclassing JSONPathEnvironment
and overriding class attributes and/or methods. Then using findall()
, finditer()
and compile()
methods of that subclass.
The default identifier tokens, like $
and @
, can be changed by setting attributes a on JSONPathEnvironment
. This example sets the root token (default $
) to be ^
.
import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nroot_token = \"^\"\ndata = {\n\"users\": [\n{\"name\": \"Sue\", \"score\": 100},\n{\"name\": \"John\", \"score\": 86},\n{\"name\": \"Sally\", \"score\": 84},\n{\"name\": \"Jane\", \"score\": 55},\n],\n\"limit\": 100,\n}\nenv = MyJSONPathEnvironment()\nuser_names = env.findall(\n\"^.users[?@.score < ^.limit].name\",\ndata,\n)\n
This table shows all available identifier token attributes.
attribute default filter_context_token_
keys_token #
root_token $
self_token @
"},{"location":"advanced/#logical-operator-tokens","title":"Logical Operator Tokens","text":"By default, we accept both Python and C-style logical operators in filter expressions. That is, not
and !
are equivalent, and
and &&
are equivalent and or
and ||
are equivalent. You can change this using class attributes on a Lexer
subclass and setting the lexer_class
attribute on a JSONPathEnvironment
.
This example changes all three logical operators to strictly match the JSONPath spec.
from jsonpath import JSONPathEnvironment\nfrom jsonpath import Lexer\nclass MyLexer(Lexer):\nlogical_not_pattern = r\"!\"\nlogical_and_pattern = r\"&&\"\nlogical_or_pattern = r\"\\|\\|\"\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nlexer_class = MyLexer\nenv = MyJSONPathEnvironment()\nenv.compile(\"$.foo[?@.a > 0 && @.b < 100]\") # OK\nenv.compile(\"$.foo[?@.a > 0 and @.b < 100]\") # JSONPathSyntaxError\n
"},{"location":"advanced/#keys-selector","title":"Keys Selector","text":"The non-standard keys selector is used to retrieve the keys/properties from a JSON Object or Python mapping. It defaults to ~
and can be changed using the keys_selector_token
attribute on a JSONPathEnvironment
subclass.
This example changes the keys selector to *~
.
from jsonpath import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nkeys_selector_token = \"*~\"\ndata = {\n\"users\": [\n{\"name\": \"Sue\", \"score\": 100},\n{\"name\": \"John\", \"score\": 86},\n{\"name\": \"Sally\", \"score\": 84},\n{\"name\": \"Jane\", \"score\": 55},\n],\n\"limit\": 100,\n}\nenv = MyJSONPathEnvironment()\nprint(env.findall(\"$.users[0].*~\", data)) # ['name', 'score']\n
"},{"location":"advanced/#array-index-limits","title":"Array Index Limits","text":"Python JSONPath limits the minimum and maximum JSON array or Python sequence indices (including slice steps) allowed in a JSONPath query. The default minimum allowed index is set to -(2**53) + 1
, and the maximum to (2**53) - 1
. When a limit is reached, a JSONPathIndexError
is raised.
You can change the minimum and maximum allowed indices using the min_int_index
and max_int_index
attributes on a JSONPathEnvironment
subclass.
from jsonpath import JSONPathEnvironment\nclass MyJSONPathEnvironment(JSONPathEnvironment):\nmin_int_index = -100\nmax_int_index = 100\nenv = MyJSONPathEnvironment()\nquery = env.compile(\"$.users[999]\")\n# jsonpath.exceptions.JSONPathIndexError: index out of range, line 1, column 8\n
"},{"location":"advanced/#subclassing-lexer","title":"Subclassing Lexer","text":"TODO:
"},{"location":"advanced/#subclassing-parser","title":"Subclassing Parser","text":"TODO:
"},{"location":"advanced/#get-item","title":"Get Item","text":"TODO:
"},{"location":"advanced/#truthiness-and-existence","title":"Truthiness and Existence","text":"TODO:
"},{"location":"advanced/#filter-infix-expressions","title":"Filter Infix Expressions","text":"TODO:
"},{"location":"api/","title":"API Reference","text":""},{"location":"api/#jsonpath.JSONPathEnvironment","title":"jsonpath.JSONPathEnvironment","text":"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 is achieved by subclassing JSONPathEnvironment
and overriding class attributes and/or methods. Some of these customizations include:
$
), self (@
) or filter context (_
) token with class attributes root_token
, self_token
and filter_context_token
.lexer_class
or parser_class
. lexer_class
must be a subclass of Lexer
and parser_class
must be a subclass of Parser
.setup_function_extensions()
getitem()
.compare()
.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
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
instance-attribute
","text":"filter_caching: bool = filter_caching\n
Enable or disable filter expression caching.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.function_extensions","title":"function_extensionsinstance-attribute
","text":"function_extensions: Dict[str, Callable[..., Any]] = {}\n
A list of function extensions available to filters.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.lexer","title":"lexerinstance-attribute
","text":"lexer: Lexer = self.lexer_class(env=self)\n
The lexer bound to this environment.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.parser","title":"parserinstance-attribute
","text":"parser: Parser = self.parser_class(env=self)\n
The parser bound to this environment.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.unicode_escape","title":"unicode_escapeinstance-attribute
","text":"unicode_escape: bool = unicode_escape\n
Enable or disable decoding of UTF-16 escape sequences found in JSONPath string literals.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.well_typed","title":"well_typedinstance-attribute
","text":"well_typed: bool = well_typed\n
Control well-typedness checks on filter function expressions.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.check_well_typedness","title":"check_well_typedness","text":"check_well_typedness(\ntoken: Token,\nfunc: FilterFunction,\nargs: List[FilterExpression],\n) -> None\n
Check the well-typedness of a function's arguments at compile-time.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.compare","title":"compare","text":"compare(left: object, operator: str, right: object) -> bool\n
Object comparison within JSONPath filters.
Override this to customize filter expression comparison operator behavior.
PARAMETER DESCRIPTIONleft
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
bool
True
if the comparison between left and right, with the
bool
given operator, is truthy. False
otherwise.
compile(path: str) -> Union[JSONPath, CompoundJSONPath]\n
Prepare a path string ready for repeated matching against different data.
PARAMETER DESCRIPTIONpath
A JSONPath as a string.
TYPE: str
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.
JSONPathSyntaxError
If path is invalid.
JSONPathTypeError
If filter functions are given arguments of an unacceptable type.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.findall","title":"findall","text":"findall(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.findall_async","title":"findall_asyncasync
","text":"findall_async(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
getitem(obj: Any, key: Any) -> Any\n
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]
.
obj
A mapping or sequence that might contain key.
TYPE: Any
key
A mapping key, sequence index or sequence slice.
TYPE: Any
async
","text":"getitem_async(obj: Any, key: object) -> Any\n
An async sequence and mapping item getter.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.is_truthy","title":"is_truthy","text":"is_truthy(obj: object) -> bool\n
Test for truthiness when evaluating JSONPath filter expressions.
In some cases, the IETF JSONPath draft 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
.
obj
Any object.
TYPE: object
bool
True
if the object exists and is not False
or 0
.
match(\npath: str,\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.setup_function_extensions","title":"setup_function_extensions","text":"setup_function_extensions() -> None\n
Initialize function extensions.
"},{"location":"api/#jsonpath.env.JSONPathEnvironment.validate_function_extension_signature","title":"validate_function_extension_signature","text":"validate_function_extension_signature(\ntoken: Token, args: List[Any]\n) -> List[Any]\n
Compile-time validation of function extension arguments.
The IETF JSONPath draft requires us to reject paths that use filter functions with too many or too few arguments.
"},{"location":"api/#jsonpath.JSONPathMatch","title":"jsonpath.JSONPathMatch","text":"A matched object with a concrete path.
ATTRIBUTE DESCRIPTIONchildren
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]]
add_child(*children: JSONPathMatch) -> None\n
Append one or more children to this match.
"},{"location":"api/#jsonpath.match.JSONPathMatch.filter_context","title":"filter_context","text":"filter_context() -> FilterContextVars\n
Return filter context data for this match.
"},{"location":"api/#jsonpath.match.JSONPathMatch.pointer","title":"pointer","text":"pointer() -> JSONPointer\n
Return a JSONPointer
pointing to this match's path.
A compiled JSONPath ready to be applied to a JSON string or Python object.
PARAMETER DESCRIPTIONenv
The JSONPathEnvironment
this path is bound to.
TYPE: JSONPathEnvironment
selectors
An iterable of JSONPathSelector
objects, as generated by a Parser
.
TYPE: Iterable[JSONPathSelector]
env
The JSONPathEnvironment
this path is bound to.
selectors
The JSONPathSelector
instances that make up this path.
"},{"location":"api/#jsonpath.path.JSONPath.empty","title":"empty","text":"
empty() -> bool\n
Return True
if this path has no selectors.
findall(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will
List[object]
be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.findall_async","title":"findall_asyncasync
","text":"findall_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
match(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.JSONPath.singular_query","title":"singular_query","text":"singular_query() -> bool\n
Return True
if this JSONPath query is a singular query.
Multiple JSONPath
s combined.
findall(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
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
.
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
List[object]
A list of matched objects. If there are no matches, the list will be empty.
RAISES DESCRIPTIONJSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.findall_async","title":"findall_asyncasync
","text":"findall_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> List[object]\n
An async version of findall()
.
finditer(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Iterable[JSONPathMatch]\n
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
.
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
Iterable[JSONPathMatch]
An iterator yielding JSONPathMatch
objects for each match.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.finditer_async","title":"finditer_asyncasync
","text":"finditer_async(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> AsyncIterable[JSONPathMatch]\n
An async version of finditer()
.
intersection(path: JSONPath) -> CompoundJSONPath\n
Intersection of this path and another path.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.match","title":"match","text":"match(\ndata: Union[\nstr, IOBase, Sequence[Any], Mapping[str, Any]\n],\n*,\nfilter_context: Optional[FilterContextVars] = None\n) -> Union[JSONPathMatch, None]\n
Return a JSONPathMatch
instance for the first object found in data.
None
is returned if there are no matches.
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
Union[JSONPathMatch, None]
A JSONPathMatch
object for the first match, or None
if there were no matches.
JSONPathSyntaxError
If the path is invalid.
JSONPathTypeError
If a filter expression attempts to use types in an incompatible way.
"},{"location":"api/#jsonpath.path.CompoundJSONPath.union","title":"union","text":"union(path: JSONPath) -> CompoundJSONPath\n
Union of this path and another path.
"},{"location":"api/#jsonpath.function_extensions.FilterFunction","title":"jsonpath.function_extensions.FilterFunction","text":" Bases: ABC
Base class for typed function extensions.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.arg_types","title":"arg_typesproperty
abstractmethod
","text":"arg_types: List[ExpressionType]\n
Argument types expected by the filter function.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.return_type","title":"return_typeproperty
abstractmethod
","text":"return_type: ExpressionType\n
The type of the value returned by the filter function.
"},{"location":"api/#jsonpath.function_extensions.filter_function.FilterFunction.__call__","title":"__call__abstractmethod
","text":"__call__(*args: Any, **kwds: Any) -> Any\n
Called the filter function.
"},{"location":"api/#jsonpath.function_extensions.ExpressionType","title":"jsonpath.function_extensions.ExpressionType","text":" Bases: Enum
The type of a filter function argument or return value.
"},{"location":"api/#jsonpath.JSONPointer","title":"jsonpath.JSONPointer","text":"Identify a single, specific value in JSON-like data, as per RFC 6901.
PARAMETER DESCRIPTIONpointer
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
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__(other: object) -> JSONPointer\n
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\".
"},{"location":"api/#jsonpath.pointer.JSONPointer.exists","title":"exists","text":"exists(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n]\n) -> bool\n
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.
data
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]
bool
True if this pointer can be resolved against data, or False otherwise.
New in version 0.9.0
"},{"location":"api/#jsonpath.pointer.JSONPointer.from_match","title":"from_matchclassmethod
","text":"from_match(match: JSONPathMatch) -> JSONPointer\n
Return a JSON Pointer for the path from a JSONPathMatch instance.
"},{"location":"api/#jsonpath.pointer.JSONPointer.from_parts","title":"from_partsclassmethod
","text":"from_parts(\nparts: Iterable[Union[int, str]],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Build a JSON Pointer from parts.
PARAMETER DESCRIPTIONparts
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
JSONPointer
A new JSONPointer
built from parts.
is_relative_to(other: JSONPointer) -> bool\n
Return True if this pointer points to a child of other.
"},{"location":"api/#jsonpath.pointer.JSONPointer.join","title":"join","text":"join(*parts: str) -> JSONPointer\n
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() -> JSONPointer\n
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
"},{"location":"api/#jsonpath.pointer.JSONPointer.resolve","title":"resolve","text":"resolve(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n],\n*,\ndefault: object = UNDEFINED\n) -> object\n
Resolve this pointer against data.
PARAMETER DESCRIPTIONdata
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
object
The object in data pointed to by this pointer.
RAISES DESCRIPTIONJSONPointerIndexError
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.
"},{"location":"api/#jsonpath.pointer.JSONPointer.resolve_parent","title":"resolve_parent","text":"resolve_parent(\ndata: Union[\nstr, IOBase, Sequence[object], Mapping[str, object]\n]\n) -> Tuple[\nUnion[Sequence[object], Mapping[str, object], None],\nobject,\n]\n
Resolve this pointer against data, return the object and its parent.
PARAMETER DESCRIPTIONdata
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, Sequence[object], Mapping[str, object]]
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.
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.
"},{"location":"api/#jsonpath.pointer.JSONPointer.to","title":"to","text":"to(\nrel: Union[RelativeJSONPointer, str],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Return a new pointer relative to this pointer.
PARAMETER DESCRIPTIONrel
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
"},{"location":"api/#jsonpath.RelativeJSONPointer","title":"jsonpath.RelativeJSONPointer","text":"A Relative JSON Pointer.
See https://www.ietf.org/id/draft-hha-relative-json-pointer-00.html
PARAMETER DESCRIPTIONrel
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(\npointer: Union[JSONPointer, str],\n*,\nunicode_escape: bool = True,\nuri_decode: bool = False\n) -> JSONPointer\n
Return a new JSONPointer relative to pointer.
PARAMETER DESCRIPTIONpointer
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
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.
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
JSONPatchError
If ops is given and any of the provided operations is malformed.
"},{"location":"api/#jsonpath.patch.JSONPatch.add","title":"add","text":"add(path: Union[str, JSONPointer], value: object) -> Self\n
Append an add operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
apply(\ndata: Union[\nstr,\nIOBase,\nMutableSequence[object],\nMutableMapping[str, object],\n]\n) -> object\n
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 DESCRIPTIONdata
The target JSON \"document\" or equivalent Python objects.
TYPE: Union[str, IOBase, MutableSequence[object], MutableMapping[str, object]]
object
Modified input data.
RAISES DESCRIPTIONJSONPatchError
When a patch operation fails.
JSONPatchTestFailure
When a test operation does not pass. JSONPatchTestFailure
is a subclass of JSONPatchError
.
asdicts() -> List[Dict[str, object]]\n
Return a list of this patch's operations as dictionaries.
"},{"location":"api/#jsonpath.patch.JSONPatch.copy","title":"copy","text":"copy(\nfrom_: Union[str, JSONPointer],\npath: Union[str, JSONPointer],\n) -> Self\n
Append a copy operation to this patch.
PARAMETER DESCRIPTIONfrom_
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]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
move(\nfrom_: Union[str, JSONPointer],\npath: Union[str, JSONPointer],\n) -> Self\n
Append a move operation to this patch.
PARAMETER DESCRIPTIONfrom_
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]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
remove(path: Union[str, JSONPointer]) -> Self\n
Append a remove operation to this patch.
PARAMETER DESCRIPTIONpath
A string representation of a JSON Pointer, or one that has already been parsed.
TYPE: Union[str, JSONPointer]
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
replace(\npath: Union[str, JSONPointer], value: object\n) -> Self\n
Append a replace operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
test(path: Union[str, JSONPointer], value: object) -> Self\n
Append a test operation to this patch.
PARAMETER DESCRIPTIONpath
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
Self
This JSONPatch
instance, so we can build a JSON Patch by chaining calls to JSON Patch operation methods.
Largely motivated by its integration with Python Liquid, Python JSONPath offers an asynchronous API that allows for items in a target data structure to be \"fetched\" lazily.
findall_async()
and finditer_async()
are asyncio equivalents to findall()
and finditer()
. By default, any class implementing the mapping or sequence interfaces, and a __getitem_async__()
method, will have __getitem_async__()
awaited instead of calling __getitem__()
when resolving mapping keys or sequence indices.
In this example, showing a lazy-loading collections of Player
objects, only the \"A\" team's players are fetched from the database, and only when they are first accessed.
from collections import abc\nfrom dataclasses import dataclass\nfrom typing import Dict\nfrom typing import Iterator\nfrom typing import List\nimport jsonpath\n@dataclass\nclass Player:\nname: str\npid: int\nrank: int\nclass LazyPlayers(abc.Mapping[str, Player]):\ndef __init__(self, names: List[str]):\nself.names = names\nself.cached_players: Dict[str, Player] = {}\ndef __len__(self) -> int:\nreturn len(self.names)\ndef __iter__(self) -> Iterator[str]:\nreturn iter(self.names)\ndef __getitem__(self, k: str) -> Player:\nif self.cached_players is None:\n# Blocking IO here\nself.cached_players = get_stuff_from_database()\nreturn self.cached_players[k]\nasync def __getitem_async__(self, k: str) -> Player:\nif self.cached_players is None:\n# Do async IO here.\nself.cached_players = await get_stuff_from_database_async()\nreturn self.cached_players[k]\ndata = {\n\"teams\": {\n\"A Team\": LazyPlayers([\"Sue\", \"Bob\"]),\n\"B Team\": LazyPlayers([\"Sally\", \"Frank\"]),\n}\n}\nbest_a_team_players = jsonpath.findall_async(\"$.teams['A Team'][?rank >= 8]\", data)\n
"},{"location":"async/#custom-async-item-getting","title":"Custom Async Item Getting","text":"TODO:
"},{"location":"cli/","title":"Command Line Interface","text":"New in version 0.9.0
Python JSONPath includes a script called json
, exposing JSONPath, JSON Pointer and JSON Patch features on the command line. Use the --version
argument to check the current version of Python JSONPath, and the --help
argument to display command information.
$ json --version\npython-jsonpath, version 0.9.0\n
$ json --help\nusage: json [-h] [--debug] [--pretty] [-v] [--no-unicode-escape] COMMAND ...\nJSONPath, JSON Pointer and JSON Patch utilities.\npositional arguments:\n COMMAND\n path Find objects in a JSON document given a JSONPath.\n pointer Resolve a JSON Pointer against a JSON document.\n patch Apply a JSON Patch to a JSON document.\noptional arguments:\n -h, --help show this help message and exit\n --debug Show stack traces. (default: False)\n --pretty Add indents and newlines to output JSON. (default: False)\n -v, --version Show the version and exit.\n --no-unicode-escape Disable decoding of UTF-16 escape sequence within paths and pointers. (default:\n False)\nUse [json COMMAND --help] for command specific help.\nUsage Examples:\n Find objects in source.json matching a JSONPath, write them to result.json.\n $ json path -q \"$.foo['bar'][?@.baz > 1]\" -f source.json -o result.json\n\n Resolve a JSON Pointer against source.json, pretty print the result to stdout.\n $ json --pretty pointer -p \"/foo/bar/0\" -f source.json\n\n Apply JSON Patch patch.json to JSON from stdin, output to result.json.\n $ cat source.json | json patch /path/to/patch.json -o result.json\n
Use json COMMAND --help
for command specific help.
$ json path --help\nusage: json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT]\nFind objects in a JSON document given a JSONPath.\noptional arguments:\n -h, --help show this help message and exit\n -q QUERY, --query QUERY\n JSONPath query string.\n -r PATH_FILE, --path-file PATH_FILE\n Text file containing a JSONPath query.\n -f FILE, --file FILE File to read the target JSON document from. Defaults to reading from the\n standard input stream.\n -o OUTPUT, --output OUTPUT\n File to write resulting objects to, as a JSON array. Defaults to the standard\n output stream.\n --no-type-checks Disables filter expression well-typedness checks.\n
"},{"location":"cli/#global-options","title":"Global Options","text":"These arguments apply to any subcommand and must be listed before the command.
"},{"location":"cli/#-debug","title":"--debug
","text":"Enable debugging. Display full stack traces, if available, when errors occur. Without the --debug
option, the following example shows a short \"json path syntax error\" message.
$ json path -q \"$.1\" -f /tmp/source.json\njson path syntax error: unexpected token '1', line 1, column 2\n
With the --debug
option, we get the stack trace triggered by JSONPathSyntaxError
.
$ json --debug path -q \"$.1\" -f /tmp/source.json\nTraceback (most recent call last):\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/bin/json\", line 8, in <module>\n sys.exit(main())\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py\", line 338, in main\n args.func(args)\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/cli.py\", line 234, in handle_path_command\n path = jsonpath.compile(args.query or args.path_file.read())\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/env.py\", line 148, in compile\n _path: Union[JSONPath, CompoundJSONPath] = JSONPath(\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/path.py\", line 49, in __init__\n self.selectors = tuple(selectors)\n File \"/home/james/.local/share/virtualenvs/jsonpath_cli-8Tb3e-ir/lib/python3.9/site-packages/jsonpath/parse.py\", line 256, in parse\n raise JSONPathSyntaxError(\njsonpath.exceptions.JSONPathSyntaxError: unexpected token '1', line 1, column 2\n
"},{"location":"cli/#-pretty","title":"--pretty
","text":"Enable pretty formatting when outputting JSON. Adds newlines and indentation to output specified with the -o
or --output
option. Without the --pretty
option, the following example output is on one line.
$ json pointer -p \"/categories/1/products/0\" -f /tmp/source.json\n{\"title\": \"Cap\", \"description\": \"Baseball cap\", \"price\": 15.0}\n
With the --pretty
option, we get nicely formatted JSON output.
$ json --pretty pointer -p \"/categories/1/products/0\" -f /tmp/source.json\n{\n \"title\": \"Cap\",\n \"description\": \"Baseball cap\",\n \"price\": 15.0\n}\n
"},{"location":"cli/#-no-unicode-escape","title":"--no-unicode-escape
","text":"Disable decoding of UTF-16 escape sequences, including surrogate paris. This can improve performance if you know your paths and pointers don't contain UTF-16 escape sequences.
$ json --no-unicode-escape path -q \"$.price_cap\" -f /tmp/source.json\n
"},{"location":"cli/#commands","title":"Commands","text":"One of the subcommands path
, pointer
or patch
must be specified, depending on whether you want to search a JSON document with a JSONPath, resolve a JSON Pointer against a JSON document or apply a JSON Patch to a JSON Document.
path
","text":"Find objects in a JSON document given a JSONPath. One of -q
/--query
or -r
/--path-file
must be given. -q
being a JSONPath given on the command line as a string, -r
being the path to a file containing a JSONPath.
json path [-h] (-q QUERY | -r PATH_FILE) [-f FILE] [-o OUTPUT]\n
"},{"location":"cli/#-q-query","title":"-q
/ --query
","text":"The JSONPath as a string.
$ json path -q \"$.price_cap\" -f /tmp/source.json\n
$ json path --query \"$.price_cap\" -f /tmp/source.json\n
"},{"location":"cli/#-r-path-file","title":"-r
/ --path-file
","text":"The path to a file containing a JSONPath.
$ json path -r /tmp/path.txt -f /tmp/source.json\n
$ json path --path-file /tmp/path.txt -f /tmp/source.json\n
"},{"location":"cli/#-f-file","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json path -q \"$.price_cap\" -f /tmp/source.json\n
$ json path -q \"$.price_cap\" --file /tmp/source.json\n
"},{"location":"cli/#-o-output","title":"-o
/ --output
","text":"The path to a file to write resulting objects to, as a JSON array. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json path -q \"$.price_cap\" -f /tmp/source.json -o result.json\n
$ json path -q \"$.price_cap\" -f /tmp/source.json --output result.json\n
"},{"location":"cli/#-no-type-checks","title":"--no-type-checks
","text":"New in version 0.10.0
Disables JSONPath filter expression well-typedness checks. The well-typedness of a filter expression is defined by the IETF JSONPath Draft specification.
"},{"location":"cli/#pointer","title":"pointer
","text":"Resolve a JSON Pointer against a JSON document. One of -p
/--pointer
or -r
/--pointer-file
must be given. -p
being a JSON Pointer given on the command line as a string, -r
being the path to a file containing a JSON Pointer.
json pointer [-h] (-p POINTER | -r POINTER_FILE) [-f FILE] [-o OUTPUT] [-u]\n
"},{"location":"cli/#-p-pointer","title":"-p
/ --pointer
","text":"An RFC 6901 formatted JSON Pointer string.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json\n
$ json pointer --pointer \"/categories/0/name\" -f /tmp/source.json\n
"},{"location":"cli/#-r-pointer-file","title":"-r
/ --pointer-file
","text":"The path to a file containing a JSON Pointer.
$ json pointer -r /tmp/pointer.txt -f /tmp/source.json\n
$ json pointer --pointer-file /tmp/pointer.txt -f /tmp/source.json\n
"},{"location":"cli/#-f-file_1","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json\n
$ json pointer -p \"/categories/0/name\" --file /tmp/source.json\n
"},{"location":"cli/#-o-output_1","title":"-o
/ --output
","text":"The path to a file to write the resulting object to. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json -o result.json\n
$ json pointer -p \"/categories/0/name\" -f /tmp/source.json --output result.json\n
"},{"location":"cli/#-u-uri-decode","title":"-u
/ --uri-decode
","text":"Enable URI decoding of the JSON Pointer. In this example, we would look for a property called \"hello world\" in the root of the target document.
$ json pointer -p \"/hello%20world\" -f /tmp/source.json -u\n
$ json pointer -p \"/hello%20world\" -f /tmp/source.json --uri-decode\n
"},{"location":"cli/#patch","title":"patch
","text":"Apply a JSON Patch to a JSON document. Unlike path
and pointer
commands, a patch can't be given as a string argument. PATCH
is a positional argument that should be a file path to a JSON Patch document or a hyphen (-
), which means the patch document will be read from the standard input stream.
json patch [-h] [-f FILE] [-o OUTPUT] [-u] PATCH\n
These examples read the patch from patch.json
and the document to modify from target.json
$ json patch /tmp/patch.json -f /tmp/target.json\n
$ cat /tmp/patch.json | json patch - -f /tmp/target.json\n
"},{"location":"cli/#-f-file_2","title":"-f
/ --file
","text":"The path to a file containing the target JSON document. If omitted or a hyphen (-
), the target JSON document will be read from the standard input stream.
$ json patch /tmp/patch.json -f /tmp/target.json\n
$ json patch /tmp/patch.json --file /tmp/target.json\n
"},{"location":"cli/#-o-output_2","title":"-o
/ --output
","text":"The path to a file to write the resulting object to. If omitted or a hyphen (-
) is given, results will be written to the standard output stream.
$ json patch /tmp/patch.json -f /tmp/target.json -o result.json\n
$ json patch /tmp/patch.json -f /tmp/target.json --output result.json\n
"},{"location":"cli/#-u-uri-decode_1","title":"-u
/ --uri-decode
","text":"Enable URI decoding of JSON Pointers in the patch document.
$ json patch /tmp/patch.json -f /tmp/target.json -u\n
$ json patch /tmp/patch.json -f /tmp/target.json --uri-decode\n
"},{"location":"custom_api/","title":"Low Level API Reference","text":"handler: python\n
handler: python\n
"},{"location":"custom_api/#jsonpath.token.Token","title":"jsonpath.token.Token","text":"A token, as returned from lex.Lexer.tokenize()
.
kind
The token's type. It is always one of the constants defined in jsonpath.token.py.
TYPE: str
value
The path substring containing text for the token.
TYPE: str
index
The index at which value starts in path.
TYPE: str
path
A reference to the complete JSONPath string from which this token derives.
TYPE: str
position() -> Tuple[int, int]\n
Return the line and column number for the start of this token.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression","title":"jsonpath.filter.FilterExpression","text":" Bases: ABC
Base class for all filter expression nodes.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.children","title":"childrenabstractmethod
","text":"children() -> List[FilterExpression]\n
Return a list of direct child expressions.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.evaluate","title":"evaluateabstractmethod
","text":"evaluate(context: FilterContext) -> object\n
Resolve the filter expression in the given context.
PARAMETER DESCRIPTIONcontext
Contextual information the expression might choose use during evaluation.
TYPE: FilterContext
object
The result of evaluating the expression.
"},{"location":"custom_api/#jsonpath.filter.FilterExpression.evaluate_async","title":"evaluate_asyncasync
abstractmethod
","text":"evaluate_async(context: FilterContext) -> object\n
An async version of evaluate
.
abstractmethod
","text":"set_children(children: List[FilterExpression]) -> None\n
Update this expression's child expressions.
children is assumed to have the same number of items as is returned by self.children, and in the same order.
"},{"location":"custom_api/#jsonpath.lex.Lexer","title":"jsonpath.lex.Lexer","text":"Tokenize a JSONPath string.
Some customization can be achieved by subclassing Lexer and setting class attributes. Then setting lexer_class
on a JSONPathEnvironment
.
key_pattern
The regular expression pattern used to match mapping keys/properties.
logical_not_pattern
The regular expression pattern used to match logical negation tokens. By default, not
and !
are equivalent.
logical_and_pattern
The regular expression pattern used to match logical and tokens. By default, and
and &&
are equivalent.
logical_or_pattern
The regular expression pattern used to match logical or tokens. By default, or
and ||
are equivalent.
"},{"location":"custom_api/#jsonpath.lex.Lexer.compile_rules","title":"compile_rules","text":"
compile_rules() -> Pattern[str]\n
Prepare regular expression rules.
"},{"location":"custom_api/#jsonpath.lex.Lexer.tokenize","title":"tokenize","text":"tokenize(path: str) -> Iterator[Token]\n
Generate a sequence of tokens from a JSONPath string.
"},{"location":"custom_api/#jsonpathparseparser","title":"jsonpath.parse.Parser","text":"TODO:
"},{"location":"custom_api/#jsonpathselectorsjsonpathselector","title":"jsonpath.selectors.JSONPathSelector","text":"TODO:
"},{"location":"custom_api/#jsonpathstreamtokenstream","title":"jsonpath.stream.TokenStream","text":"TODO:
"},{"location":"exceptions/","title":"Exceptions","text":"Each of the following exceptions has a token
property, referencing the Token
that caused the error. You can use Token.position()
to get the token's line and column number.
Bases: Exception
Base exception for all errors.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Optional[Token]
DEFAULT: None
Bases: JSONPathError
An exception raised when parsing a JSONPath string.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
Bases: JSONPathError
An exception raised due to a type error.
This should only occur at when evaluating filter expressions.
"},{"location":"exceptions/#jsonpath.JSONPathIndexError","title":"jsonpath.JSONPathIndexError","text":" Bases: JSONPathError
An exception raised when an array index is out of range.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
Bases: JSONPathError
An exception raised when an unknown function extension is called.
PARAMETER DESCRIPTIONargs
Arguments passed to Exception
.
TYPE: object
DEFAULT: ()
token
The token that caused the error.
TYPE: Token
A filter function is a named function that can be called as part of a filter selector expression. Here we describe built-in filters. You can define your own function extensions too.
"},{"location":"functions/#count","title":"count()
","text":"count(obj: object) -> Optional[int]\n
Return the number of items in obj. If the object does not respond to Python's len()
function, None
is returned.
$.categories[?count(@.products.*) >= 2]\n
"},{"location":"functions/#isinstance","title":"isinstance()
","text":"New in version 0.6.0
isinstance(obj: object, t: str) -> bool\n
Return True
if the type of obj matches t. This function allows t to be one of several aliases for the real Python \"type\". Some of these aliases follow JavaScript/JSON semantics.
For example :
$.categories[?isinstance(@.length, 'number')]\n
And is()
is an alias for isinstance()
:
$.categories[?is(@.length, 'number')]\n
"},{"location":"functions/#length","title":"length()
","text":"length(obj: object) -> Optional[int]\n
Return the number of items in the input object. If the object does not respond to Python's len()
function, None
is returned.
$.categories[?length(@) > 1]\n
"},{"location":"functions/#match","title":"match()
","text":"match(obj: object, pattern: str) -> bool\n
Return True
if obj is a string and is a full match to the regex pattern.
$..products[?match(@.title, \".+ainers.+\")]\n
If pattern is a string literal, it will be compiled at compile time, and raise a JSONPathTypeError
at compile time if it's invalid.
If pattern is a query and the result is not a valid regex, False
is returned.
search()
","text":"search(obj: object, pattern: str) -> bool\n
Return True
if obj is a string and it contains the regexp pattern.
$..products[?search(@.title, \"ainers\")]\n
If pattern is a string literal, it will be compiled at compile time, and raise a JSONPathTypeError
at compile time if it's invalid.
If pattern is a query and the result is not a valid regex, False
is returned.
typeof()
","text":"New in version 0.6.0
typeof(obj: object) -> str\n
Return the type of obj as a string. The strings returned from this function use JavaScript/JSON terminology like \"string\", \"array\" and \"object\", much like the result of JavaScript's typeof
operator.
$.categories[?typeof(@.length) == 'number']\n
type()
is and alias for typeof()
.
jsonpath.function_extensions.TypeOf
takes a single_number_type
argument, which controls the behavior of typeof()
when given and int or float. By default, single_number_type
is True
and \"number\"
is returned. Register a new instance of TypeOf
with a JSONPathEnvironment
with single_number_type
set to False
and \"int\"
and \"float\"
will be returned when given integers and floats, respectively.
single_number_type
is False
float \"number\" or \"float\" if single_number_type
is False
"},{"location":"functions/#value","title":"value()
","text":"value(nodes: object) -> object | undefined\n
Return the first value from nodes resulting from a JSONPath query, if there is only one node, or undefined
otherwise.
$..products[?value(@.price) == 9]\n
"},{"location":"pointers/","title":"JSON Pointers","text":"New in version 0.8.0
JSON Pointer (RFC 6901) is a string syntax for targeting a single value (JSON object, array or scalar) in a JSON document. Whereas a JSONPath has the potential to yield many values from a JSON document, a JSON Pointer can resolve to at most one value.
JSON Pointers are a fundamental part of JSON Patch (RFC 6902). Each patch operation must have at least one pointer, identifying the target value.
Note
We have extended RFC 6901 to handle our non-standard JSONPath keys selector and index/property pointers from Relative JSON Pointer.
"},{"location":"pointers/#resolvedata","title":"resolve(data)
","text":"Resolve this pointer against data. data can be a file-like object or string containing JSON formatted data, or a Python Mapping
or Sequence
, like a dictionary or list.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.resolve(example_data)) # 1\n
"},{"location":"pointers/#resolve_parentdata","title":"resolve_parent(data)
","text":"Resolve this pointer against data, return the object and its parent as a (parent, object)
tuple.
If object does not exist in data but parent does, (parent, UNDEFINED)
will be returned. Where jsonpath.pointer.UNDEFINED
indicates the lack of a value.
If this pointer points to the JSON document root, parent will be None
.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.resolve_parent(example_data)) # ([1, 2, 3], 1)\n# 'thing' does not exist\npointer = JSONPointer(\"/foo/thing\")\nprint(pointer.resolve_parent(example_data)) # ({'bar': [1, 2, 3]}, <jsonpath.pointer._Undefined object at 0x7f0c7cf77040>)\npointer = JSONPointer(\"\")\nprint(pointer.resolve_parent(example_data)) # (None, {'foo': {'bar': [1, 2, 3]}})\n
"},{"location":"pointers/#existsdata","title":"exists(data)
","text":"New in version 0.9.0
Return True if this pointer can be resolved against data, or False otherwise. 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.
from jsonpath import JSONPointer\nexample_data = {\"foo\": {\"bar\": [1, 2, 3]}, \"baz\": False}\npointer = JSONPointer(\"/foo/bar/0\")\nprint(pointer.exists(example_data)) # True\npointer = JSONPointer(\"/foo/bar/9\")\nprint(pointer.exists(example_data)) # False\npointer = JSONPointer(\"/baz\")\nprint(pointer.exists(example_data)) # True\n
"},{"location":"pointers/#joinparts","title":"join(*parts)
","text":"New in version 0.9.0
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.
join()
is equivalent to using the slash (/
) operator for each argument.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nprint(pointer) # /foo/bar\nprint(pointer.join(\"baz\")) # /foo/bar/baz\nprint(pointer.join(\"baz\", \"0\")) # /foo/bar/baz/0\n
"},{"location":"pointers/#parent","title":"parent()
","text":"New in version 0.9.0
Return this pointer's parent as a new JSONPointer
. If this pointer points to the document root, self is returned.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nprint(pointer) # /foo/bar\nprint(pointer.parent()) # /foo\n
"},{"location":"pointers/#is_relative_topointer","title":"is_relative_to(pointer)
","text":"Return True if this pointer points to a child of the argument pointer, which must be a JSONPointer
instance.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/foo/bar\")\nanother_pointer = JSONPointer(\"/foo/bar/0\")\nprint(another_pointer.is_relative_to(pointer)) # True\nanother_pointer = JSONPointer(\"/foo/baz\")\nprint(another_pointer.is_relative_to(pointer)) # False\n
"},{"location":"pointers/#torel","title":"to(rel)
","text":"New in version 0.9.0
Return a new JSONPointer
relative to this pointer. rel should be a RelativeJSONPointer
instance or a string following Relative JSON Pointer syntax.
from jsonpath import JSONPointer\ndata = {\"foo\": {\"bar\": [1, 2, 3], \"baz\": [4, 5, 6]}}\npointer = JSONPointer(\"/foo/bar/2\")\nprint(pointer.resolve(data)) # 3\nprint(pointer.to(\"0-1\").resolve(data)) # 2\nprint(pointer.to(\"2/baz/2\").resolve(data)) # 6\n
A RelativeJSONPointer
can be instantiated for repeated application to multiple different pointers.
from jsonpath import JSONPointer\nfrom jsonpath import RelativeJSONPointer\ndata = {\"foo\": {\"bar\": [1, 2, 3], \"baz\": [4, 5, 6], \"some\": \"thing\"}}\nsome_pointer = JSONPointer(\"/foo/bar/0\")\nanother_pointer = JSONPointer(\"/foo/baz/2\")\nrel = RelativeJSONPointer(\"2/some\")\nprint(rel.to(some_pointer).resolve(data)) # thing\nprint(rel.to(another_pointer).resolve(data)) # thing\n
"},{"location":"pointers/#slash-operator","title":"Slash Operator","text":"New in version 0.9.0
The slash operator allows you to create pointers that are children of an existing pointer.
from jsonpath import JSONPointer\npointer = JSONPointer(\"/users\")\nchild_pointer = pointer / \"score\" / \"0\"\nanother_child_pointer = pointer / \"score/1\"\nprint(child_pointer) # \"/users/score/0\"\nprint(another_child_pointer) # \"/users/score/1\"\n
"},{"location":"quickstart/","title":"Quick Start","text":"This page gets you started using JSONPath, JSON Pointer and JSON Patch wih Python. See JSONPath Syntax for information on JSONPath selector syntax.
"},{"location":"quickstart/#findallpath-data","title":"findall(path, data)
","text":"Find all objects matching a JSONPath with jsonpath.findall()
. It takes, as arguments, a JSONPath string and some data object. It always returns a list of objects selected from data, never a scalar value.
data can be a file-like object or string containing JSON formatted data, or a Python Mapping
or Sequence
, like a dictionary or list. In this example we select user names from a dictionary containing a list of user dictionaries.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nuser_names = jsonpath.findall(\"$.users.*.name\", data)\n
Where user_names
is now equal to:
[\"Sue\", \"John\", \"Sally\", \"Jane\"]\n
If the same data were in a file called users.json
, we might use findall()
like this:
import jsonpath\nwith open(\"users.json\") as fd:\nuser_names = jsonpath.findall(\"$.users.*.name\", fd)\n
"},{"location":"quickstart/#finditerpath-data","title":"finditer(path, data)
","text":"Use jsonpath.finditer()
to iterate over instances of jsonpath.JSONPathMatch
for every object in data that matches path. It accepts the same arguments as findall()
, a path string and data from which to select matches.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nmatches = jsonpath.finditer(\"$.users.*.name\", data)\nfor match in matches:\nprint(matches)\n
The string representation of a JSONPathMatch
shows the matched object and the canonical path to that object.
'Sue' @ $['users'][0]['name']\n'John' @ $['users'][1]['name']\n'Sally' @ $['users'][2]['name']\n'Jane' @ $['users'][3]['name']\n
The selected object is available from a JSONPathMatch
as obj
and its path, as a string, as path
. Other useful properties of JSONPathMatch
include a reference to the parent match, a list of child matches, and a parts
tuple of keys and indices that make up the path.
compile(path)
","text":"When you have a JSONPath that needs to be matched against different data repeatedly, you can compile the path ahead of time using jsonpath.compile()
. It takes a path as a string and returns a JSONPath
instance. JSONPath
has findall()
and finditer()
methods that behave similarly to package-level findall()
and finditer()
, just without the path
argument.
import jsonpath\nsome_data = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n]\n}\nother_data = {\n\"users\": [\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\npath = jsonpath.compile(\"$.users.*.name\")\nsome_users = path.findall(some_data)\nother_users = path.findall(other_data)\n
"},{"location":"quickstart/#matchpath-data","title":"match(path, data)
","text":"New in version 0.8.0
Get a jsonpath.JSONPathMatch
instance for the first match found in data. If there are no matches, None
is returned. match()
accepts the same arguments as findall()
.
import jsonpath\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nmatch = jsonpath.match(\"$.users[?@.score > 85].name\", data)\nif match:\nprint(match) # 'Sue' @ $['users'][0]['name']\nprint(match.obj) # Sue\n
"},{"location":"quickstart/#pointerresolvepointer-data","title":"pointer.resolve(pointer, data)
","text":"New in version 0.8.0
Resolve a JSON Pointer (RFC 6901) against some data. A JSON Pointer references a single object on a specific \"path\" in a JSON document. Here, pointer can be a string representation of a JSON Pointer or a list of parts that make up a pointer. data can be a file-like object or string containing JSON formatted data, or equivalent Python objects.
from jsonpath import pointer\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n{\n\"name\": \"Sally\",\n\"score\": 84,\n},\n{\n\"name\": \"Jane\",\n\"score\": 55,\n},\n]\n}\nsue_score = pointer.resolve(\"/users/0/score\", data)\nprint(sue_score) # 100\njane_score = pointer.resolve([\"users\", 3, \"score\"], data)\nprint(jane_score) # 55\n
If the pointer can't be resolved against the target JSON document - due to missing keys/properties or out of range indices - a JSONPointerIndexError
, JSONPointerKeyError
or JSONPointerTypeError
will be raised, each of which inherit from JSONPointerResolutionError
. A default value can be given, which will be returned in the event of a JSONPointerResolutionError
.
from jsonpath import pointer\ndata = {\n\"users\": [\n{\n\"name\": \"Sue\",\n\"score\": 100,\n},\n{\n\"name\": \"John\",\n\"score\": 86,\n},\n]\n}\nsue_score = pointer.resolve(\"/users/99/score\", data, default=0)\nprint(sue_score) # 0\n
See also JSONPathMatch.pointer()
, which builds a JSONPointer
from a JSONPathMatch
.
patch.apply(patch, data)
","text":"New in version 0.8.0
Apply a JSON Patch (RFC 6902) to some data. A JSON Patch defines update operation to perform on a JSON document.
patch can be a string or file-like object containing a valid JSON Patch document, or an iterable of dictionaries.
data is the target JSON document to modify. 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.
from jsonpath import patch\npatch_operations = [\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"foo\": {}}},\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"bar\": []}},\n{\"op\": \"copy\", \"from\": \"/some/other\", \"path\": \"/some/foo/else\"},\n{\"op\": \"add\", \"path\": \"/some/foo/bar/-\", \"value\": 1},\n]\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(patch_operations, data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
Use the JSONPatch class to create a patch for repeated application.
from jsonpath import JSONPatch\npatch = JSONPatch(\n[\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"foo\": {}}},\n{\"op\": \"add\", \"path\": \"/some/foo\", \"value\": {\"bar\": []}},\n{\"op\": \"copy\", \"from\": \"/some/other\", \"path\": \"/some/foo/else\"},\n{\"op\": \"add\", \"path\": \"/some/foo/bar/-\", \"value\": 1},\n]\n)\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
JSONPatch also offers a builder API for constructing JSON patch documents. We use strings as JSON Pointers in this example, but existing JSONPointer instances are OK too.
from jsonpath import JSONPatch\npatch = (\nJSONPatch()\n.add(\"/some/foo\", {\"foo\": []})\n.add(\"/some/foo\", {\"bar\": []})\n.copy(\"/some/other\", \"/some/foo/else\")\n.add(\"/some/foo/bar/-\", \"/some/foo/else\")\n)\ndata = {\"some\": {\"other\": \"thing\"}}\npatch.apply(data)\nprint(data) # {'some': {'other': 'thing', 'foo': {'bar': [1], 'else': 'thing'}}}\n
"},{"location":"quickstart/#whats-next","title":"What's Next?","text":"Read about user-defined filter functions at Function Extensions, or see how to make extra data available to filters with Extra Filter Context.
findall()
, finditer()
and compile()
are shortcuts that use the defaultJSONPathEnvironment
. jsonpath.findall(path, data)
is equivalent to:
jsonpath.JSONPathEnvironment().compile(path).findall(data)\n
If you would like to customize Python JSONPath, see Advanced Usage.
"},{"location":"syntax/","title":"JSONPath Syntax","text":"Python JSONPath's default syntax is an opinionated combination of JSONPath features from existing, popular implementations, and much of the IETF JSONPath draft. If you're already familiar with JSONPath syntax, skip to notable differences.
Imagine a JSON document as a tree structure, where each object (mapping) and array can contain more objects, arrays and scalar values. Every object, array and scalar value is a node in the tree, and the outermost object or array is the \"root\" node.
For our purposes, a JSON \"document\" could be a file containing valid JSON data, a Python string containing valid JSON data, or a Python Object
made up of dictionaries (or any Mapping), lists (or any Sequence), strings, etc.
We chain selectors together to retrieve nodes from the target document. Each selector operates on the nodes matched by preceding selectors. What follows is a description of those selectors.
"},{"location":"syntax/#selectors","title":"Selectors","text":""},{"location":"syntax/#root","title":"Root ($
)","text":"$
refers to the first node in the target document, be it an object or an array. Unless referencing the root node from inside a filter expression, $
is optional. The following two examples are equivalent.
$.categories.*.name\n
categories.*.name\n
An empty path or a path containing just the root ($
) selector returns the input data in its entirety.
.thing
, [thing]
or ['thing']
)","text":"Select nodes by property/key name using dot notation (.something
) or bracket notation ([something]
). If a target property/key contains reserved characters, it must use bracket notation and be enclosed in quotes (['thing']
).
A dot in front of bracket notation is OK, but unnecessary. The following examples are equivalent.
$.categories[0].name\n
$.categories[0][name]\n
$.categories[0]['name']\n
"},{"location":"syntax/#array-indices-0-or-1","title":"Array indices ([0]
or [-1]
)","text":"Select an item from an array by its index. Indices are zero-based and enclosed in brackets. If the index is negative, items are selected from the end of the array. Considering example data from the top of this page, the following examples are equivalent.
$.categories[0]\n
$.categories[-1]\n
"},{"location":"syntax/#wildcard-or","title":"Wildcard (.*
or [*]
)","text":"Select all elements from an array or all values from an object using *
. These two examples are equivalent.
$.categories[0].products.*\n
$.categories[0].products[*]\n
"},{"location":"syntax/#keys-or","title":"Keys (.~
or [~]
)","text":"New in version 0.6.0
Select keys/properties from an object using ~
.
$.categories.~\n
$.categories[~]\n
"},{"location":"syntax/#slices-0-1-or-10-1","title":"Slices ([0:-1]
or [-1:0:-1]
)","text":"Select a range of elements from an array using slice notation. The start index, stop index and step are all optional. These examples are equivalent.
$.categories[0:]\n
$.categories[0:-1:]\n
$.categories[0:-1:1]\n
$.categories[::]\n
"},{"location":"syntax/#lists-1-2-1020","title":"Lists ([1, 2, 10:20]
)","text":"Select multiple indices, slices or properties using list notation (sometimes known as a \"union\" or \"segment\", we use \"union\" to mean something else).
$..products.*.[title, price]\n
"},{"location":"syntax/#recursive-descent","title":"Recursive descent (..
)","text":"The ..
selector visits every node beneath the current selection. If a property selector, using dot notation, follows ..
, the dot is optional. These two examples are equivalent.
$..title\n
$...title\n
"},{"location":"syntax/#filters-expression","title":"Filters ([?EXPRESSION]
)","text":"Filters allow you to remove nodes from a selection using a Boolean expression. A filter query is a JSONPath query nested within a filter expression. Every filter query must start with the root identifier ($
), the current node identifier (@
) or the filter context identifier (_
).
$..products[?(@.price < $.price_cap)]\n
$..products[?@.price < $.price_cap]\n
When filtering a mapping-like object, #
references the current key/property and @
references the current value associated with #
. When filtering a sequence-like object, @
references the current item and #
will hold the item's index in the sequence.
Comparison operators include ==
, !=
, <
, >
, <=
and >=
. Plus <>
as an alias for !=
.
in
and contains
are membership operators. left in right
is equivalent to right contains left
.
&&
and ||
are logical operators and terms can be grouped with parentheses. and
and or
work too.
=~
matches the left value with a regular expression literal. Regular expressions use a syntax similar to that found in JavaScript, where the pattern to match is surrounded by slashes, optionally followed by flags.
$..products[?(@.description =~ /.*trainers/i)]\n
A filter query on its own - one that is not part of a comparison expression - is an existence test. We also support comparing a filter query to the special undefined
keyword. These two example are equivalent.
$..products[?!@.sale_price]\n
$..products[?@.sale_price == undefined]\n
Filter expressions can call predefined function extensions too.
$.categories[?count(@.products.*) >= 2]\n
"},{"location":"syntax/#union-and-intersection","title":"Union (|
) and intersection (&
)","text":"Union (|
) and intersection (&
) are similar to Python's set operations, but we don't dedupe the matches (matches will often contain unhashable objects).
The |
operator combines matches from two or more paths. This example selects a single list of all prices, plus the price cap as the last element.
$..products.*.price | $.price_cap\n
The &
operator produces matches that are common to both left and right paths. This example would select the list of products that are common to both the \"footwear\" and \"headwear\" categories.
$.categories[?(@.name == 'footwear')].products.* & $.categories[?(@.name == 'headwear')].products.*\n
Note that |
and &
are not allowed inside filter expressions.
This is a list of things that you might find in other JSONPath implementation that we don't support (yet).
selector.func()
.jsonpath.findall()
, never a scalar value.JSONPathMatch
instances to JSONPointer
s, and a JSONPatch
builder API for modifying JSON-like data structures using said pointers.And this is a list of areas where we deviate from the IETF JSONPath draft.
$
) is optional and paths starting with a dot (.
) are OK. .thing
is the same as $.thing
, as is thing
, $[thing]
and $[\"thing\"]
.match()
and search()
filter functions use Python's standard library re
module, which, at least, doesn't support Unicode properties. We might add an implementation of match()
and search()
using the third party regex package in the future.$..
is equivalent to $..*
.undefined
as well as implicit existence tests.1.
is equivalent to 1.0
.And this is a list of features that are uncommon or unique to Python JSONPath.
in
and contains
, plus list/array literals.|
is a union operator, where matches from two or more JSONPaths are combined. This is not part of the Python API, but built-in to the JSONPath syntax.&
is an intersection operator, where we exclude matches that don't exist in both left and right paths. This is not part of the Python API, but built-in to the JSONPath syntax.#
is the current key/property or index identifier when filtering a mapping or sequence._
is a filter context selector. With usage similar to $
and @
, _
exposes arbitrary data from the filter_context
argument to findall()
and finditer()
.~
is a \"keys\" or \"properties\" selector...
)[?EXPRESSION]
)Filters allow you to remove nodes from a selection using a Boolean expression. When filtering a mapping-like object, #
references the current key/property and @
references the current value associated with #
. When filtering a sequence-like object, @
references the current item and #
will hold the item's index in the sequence.
Filters allow you to remove nodes from a selection using a Boolean expression. A filter query is a JSONPath query nested within a filter expression. Every filter query must start with the root identifier ($
), the current node identifier (@
) or the filter context identifier (_
).
When filtering a mapping-like object, #
references the current key/property and @
references the current value associated with #
. When filtering a sequence-like object, @
references the current item and #
will hold the item's index in the sequence.
Comparison operators include ==
, !=
, <
, >
, <=
and >=
. Plus <>
as an alias for !=
.
in
and contains
are membership operators. left in right
is equivalent to right contains left
.
&&
and ||
are logical operators, and
and or
work too.
&&
and ||
are logical operators and terms can be grouped with parentheses. and
and or
work too.
=~
matches the left value with a regular expression literal. Regular expressions use a syntax similar to that found in JavaScript, where the pattern to match is surrounded by slashes, optionally followed by flags.
Filter expressions can call predefined function extensions too.
-$.categories[?count(@.products.*) >= 2]
+A filter query on its own - one that is not part of a comparison expression - is an existence test. We also support comparing a filter query to the special undefined
keyword. These two example are equivalent.
+
-undefined
can be used to filter on the absence of a key/property or an undefined value returned from a filter function. missing
is an alias for undefined
.
+Filter expressions can call predefined function extensions too.
+
Union (|
) and intersection (&
)
Union (|
) and intersection (&
) are similar to Python's set operations, but we don't dedupe the matches (matches will often contain unhashable objects).
The |
operator combines matches from two or more paths. This example selects a single list of all prices, plus the price cap as the last element.
-