Skip to content

Commit a92b721

Browse files
committed
Extra filter context data.
1 parent 86e872a commit a92b721

8 files changed

Lines changed: 149 additions & 51 deletions

File tree

‎jsonpath/env.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
"""Core JSONPath objects."""
1+
"""Core JSONPath configuration object."""
22
from __future__ import annotations
33

44
import json
@@ -10,6 +10,7 @@
1010
from typing import Iterable
1111
from typing import List
1212
from typing import Mapping
13+
from typing import Optional
1314
from typing import Sequence
1415
from typing import Union
1516

@@ -19,10 +20,11 @@
1920
from .filter import UNDEFINED
2021

2122
from .lex import Lexer
23+
from .match import FilterContextVars
2224
from .parse import Parser
2325

24-
from .path import JSONPath
2526
from .path import CompoundJSONPath
27+
from .path import JSONPath
2628

2729
from .stream import TokenStream
2830

@@ -40,7 +42,7 @@ class JSONPathEnvironment:
4042
root_token = "$"
4143
self_token = "@"
4244
union_token = "|"
43-
context_vars_token = "#"
45+
filter_context_token = "#"
4446

4547
# Unquoted mapping keys (JSON object properties) should match this
4648
# pattern. It should be raw/escaped.
@@ -93,6 +95,8 @@ def findall(
9395
self,
9496
path: str,
9597
data: Union[str, Sequence[Any], Mapping[str, Any]],
98+
*,
99+
filter_context: Optional[FilterContextVars] = None,
96100
) -> List[object]:
97101
"""Find all objects in `data` matching the given JSONPath. Return a
98102
list of matches, or an empty list if no matches.
@@ -105,12 +109,14 @@ def findall(
105109
_path = self.compile(path)
106110
if isinstance(data, str):
107111
data = json.loads(data)
108-
return _path.findall(data)
112+
return _path.findall(data, filter_context=filter_context)
109113

110114
def finditer(
111115
self,
112116
path: str,
113117
data: Union[str, Sequence[Any], Mapping[str, Any]],
118+
*,
119+
filter_context: Optional[FilterContextVars] = None,
114120
) -> Iterable[object]:
115121
"""Return an iterator yielding :class:`JSONPathMatch` objects for each
116122
match of the path in the given `data`.
@@ -122,7 +128,9 @@ def finditer(
122128
_path = self.compile(path)
123129
if isinstance(data, str):
124130
data = json.loads(data)
125-
return _path.finditer(data)
131+
return _path.finditer(data, filter_context=filter_context)
132+
133+
# TODO: async findall and finditer
126134

127135
def getitem(self, obj: Any, key: Any) -> Any:
128136
"""Sequence and mapping item getter used throughout JSONPath resolution."""

‎jsonpath/filter.py‎

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -308,20 +308,39 @@ def __str__(self) -> str:
308308
return str(self.path)
309309

310310
def evaluate(self, context: FilterContext) -> object:
311-
return self.path.findall(context.root) or UNDEFINED
311+
matches = self.path.findall(context.root)
312+
if not matches:
313+
return UNDEFINED
314+
if len(matches) == 1:
315+
return matches[0]
316+
return matches
312317

313318
async def evaluate_async(self, context: FilterContext) -> object:
314-
return await self.path.findall_async(context.root) or UNDEFINED
319+
matches = await self.path.findall_async(context.root)
320+
if not matches:
321+
return UNDEFINED
322+
if len(matches) == 1:
323+
return matches[0]
324+
return matches
315325

316326

317-
class GlobalPath(Path):
327+
class FilterContextPath(Path):
318328
def __str__(self) -> str:
319329
path_repr = str(self.path)
320330
return "#" + path_repr[1:]
321331

322332
def evaluate(self, context: FilterContext) -> object:
323-
print(context)
324-
return self.path.findall(context.globals) or UNDEFINED
333+
matches = self.path.findall(context.extra_context)
334+
if not matches:
335+
return UNDEFINED
336+
if len(matches) == 1:
337+
return matches[0]
338+
return matches
325339

326340
async def evaluate_async(self, context: FilterContext) -> object:
327-
return await self.path.findall_async(context.globals) or UNDEFINED
341+
matches = await self.path.findall_async(context.extra_context)
342+
if not matches:
343+
return UNDEFINED
344+
if len(matches) == 1:
345+
return matches[0]
346+
return matches

‎jsonpath/lex.py‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from .token import TOKEN_BRACKET_PROPERTY
1616
from .token import TOKEN_COMMA
1717
from .token import TOKEN_CONTAINS
18-
from .token import TOKEN_GLOBAL
18+
from .token import TOKEN_FILTER_CONTEXT
1919
from .token import TOKEN_DDOT
2020
from .token import TOKEN_DOT_INDEX
2121
from .token import TOKEN_DOT_PROPERTY
@@ -68,8 +68,6 @@
6868
if TYPE_CHECKING:
6969
from . import JSONPathEnvironment
7070

71-
# TODO: A "scope" operator (like `$` and `@`, but for arbitrary scope lookup)
72-
7371

7472
class Lexer:
7573
"""Tokenize a JSONPath string."""
@@ -147,7 +145,7 @@ def compile_rules(self) -> Pattern[str]:
147145
(TOKEN_SELF, re.escape(self.env.self_token)),
148146
(TOKEN_UNION, re.escape(self.env.union_token)),
149147
(TOKEN_INTERSECTION, re.escape(self.env.intersection_token)),
150-
(TOKEN_GLOBAL, re.escape(self.env.context_vars_token)),
148+
(TOKEN_FILTER_CONTEXT, re.escape(self.env.filter_context_token)),
151149
(TOKEN_AND, self.bool_and_pattern),
152150
(TOKEN_OR, self.bool_or_pattern),
153151
(TOKEN_IN, r"in"),

‎jsonpath/match.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,39 @@
1-
""""""
1+
"""The JSONPath match object, as returned from :meth:`JSONPath.finditer`."""
22

33
from typing import Any
44
from typing import Mapping
55
from typing import Sequence
66
from typing import Union
77

8+
FilterContextVars = Mapping[str, Any]
9+
810

911
# pylint: disable=too-few-public-methods
1012
class JSONPathMatch:
1113
"""Bind a matched object to its path."""
1214

13-
__slots__ = ("path", "obj", "root")
15+
__slots__ = ("_filter_context", "obj", "path", "root")
1416

1517
def __init__(
1618
self,
1719
*,
18-
path: str,
20+
filter_context: FilterContextVars,
1921
obj: object,
22+
path: str,
2023
root: Union[Sequence[Any], Mapping[str, Any]],
2124
) -> None:
2225
self.path = path
2326
self.obj = obj
2427
self.root = root
28+
self._filter_context = filter_context
2529

2630
def __str__(self) -> str:
2731
return f"{_truncate(str(self.obj), 5)} @ {_truncate(self.path, 5)}"
2832

33+
def filter_context(self) -> FilterContextVars:
34+
""""""
35+
return self._filter_context
36+
2937

3038
def _truncate(val: str, num: int, end: str = "...") -> str:
3139
# Replaces consecutive whitespace with a single newline.

‎jsonpath/parse.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from .filter import RegexLiteral
2727
from .filter import RootPath
2828
from .filter import SelfPath
29+
from .filter import FilterContextPath
2930
from .filter import StringLiteral
3031
from .filter import TRUE
3132
from .filter import UNDEFINED_LITERAL
@@ -49,6 +50,7 @@
4950
from .token import TOKEN_EOF
5051
from .token import TOKEN_EQ
5152
from .token import TOKEN_FALSE
53+
from .token import TOKEN_FILTER_CONTEXT
5254
from .token import TOKEN_FILTER_END
5355
from .token import TOKEN_FILTER_START
5456
from .token import TOKEN_FLOAT
@@ -166,6 +168,7 @@ def __init__(self, *, env: JSONPathEnvironment) -> None:
166168
TOKEN_RE_PATTERN: self.parse_regex,
167169
TOKEN_ROOT: self.parse_root_path,
168170
TOKEN_SELF: self.parse_self_path,
171+
TOKEN_FILTER_CONTEXT: self.parse_filter_context_path,
169172
TOKEN_STRING: self.parse_string_literal,
170173
TOKEN_TRUE: self.parse_boolean,
171174
TOKEN_UNDEFINED: self.parse_undefined,
@@ -382,6 +385,12 @@ def parse_self_path(self, stream: TokenStream) -> FilterExpression:
382385
JSONPath(env=self.env, selectors=self.parse_path(stream, in_filter=True))
383386
)
384387

388+
def parse_filter_context_path(self, stream: TokenStream) -> FilterExpression:
389+
stream.next_token()
390+
return FilterContextPath(
391+
JSONPath(env=self.env, selectors=self.parse_path(stream, in_filter=True))
392+
)
393+
385394
def parse_regex(self, stream: TokenStream) -> FilterExpression:
386395
pattern = re.escape(stream.current.value)
387396
if stream.peek.kind == TOKEN_RE_FLAGS:

0 commit comments

Comments
 (0)