Skip to content

Commit b8ebc4d

Browse files
committed
Canonical paths.
1 parent a212c9e commit b8ebc4d

5 files changed

Lines changed: 58 additions & 70 deletions

File tree

‎jsonpath/filter.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def __init__(self, *, value: LITERAL_EXPRESSION_T) -> None:
9595
self.value = value
9696

9797
def __str__(self) -> str:
98-
return repr(self.value)
98+
return repr(self.value).lower()
9999

100100
def __eq__(self, other: object) -> bool:
101101
return self.value == other

‎jsonpath/lex.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@ def compile_rules(self) -> Pattern[str]:
141141
(TOKEN_FILTER_END, r"\)\s*]"),
142142
(TOKEN_BRACKET_PROPERTY, self.bracketed_property_pattern),
143143
(TOKEN_DOT_PROPERTY, self.dot_property_pattern),
144+
# TODO: Scientific notation 1e2 1e+2 1e-2 1.2e3
144145
(TOKEN_FLOAT, r"-?\d+\.\d*"),
145146
(TOKEN_INT, r"-?\d+\b"),
146147
(TOKEN_DDOT, r"\.\."),

‎jsonpath/selectors.py‎

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def resolve_async(
4848
class PropertySelector(JSONPathSelector):
4949
"""A JSONPath property."""
5050

51-
__slots__ = ("name", "path")
51+
__slots__ = ("name",)
5252

5353
def __init__(
5454
self,
@@ -59,20 +59,17 @@ def __init__(
5959
) -> None:
6060
super().__init__(env=env, token=token)
6161
self.name = name
62-
self.path = str(self)
6362

6463
def __str__(self) -> str:
65-
if self.env.re_key.fullmatch(self.name):
66-
return f".{self.name}"
67-
return f'["{self.name}"]'
64+
return f"['{self.name}']"
6865

6966
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
7067
for match in matches:
7168
if not isinstance(match.obj, Mapping):
7269
continue
7370
try:
7471
yield JSONPathMatch(
75-
path=match.path + self.path,
72+
path=match.path + f"['{self.name}']",
7673
obj=self.env.getitem(match.obj, self.name),
7774
root=match.root,
7875
filter_context=match.filter_context(),
@@ -89,7 +86,7 @@ async def resolve_async(
8986
continue
9087
try:
9188
yield JSONPathMatch(
92-
path=match.path + self.path,
89+
path=match.path + f"['{self.name}']",
9390
obj=await self.env.getitem_async(match.obj, self.name),
9491
root=match.root,
9592
filter_context=match.filter_context(),
@@ -101,7 +98,7 @@ async def resolve_async(
10198
class IndexSelector(JSONPathSelector):
10299
"""Dotted and bracketed sequence access by index."""
103100

104-
__slots__ = ("index", "path", "_as_key")
101+
__slots__ = ("index", "_as_key")
105102

106103
def __init__(
107104
self,
@@ -112,7 +109,6 @@ def __init__(
112109
) -> None:
113110
super().__init__(env=env, token=token)
114111
self.index = index
115-
self.path = str(self)
116112
self._as_key = str(self.index)
117113

118114
def __str__(self) -> str:
@@ -124,7 +120,7 @@ def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
124120
# Try the string representation of the index as a key.
125121
try:
126122
yield JSONPathMatch(
127-
path=f'{match.path}["{self.index}"]',
123+
path=f"{match.path}['{self.index}']",
128124
obj=self.env.getitem(match.obj, self._as_key),
129125
root=match.root,
130126
filter_context=match.filter_context(),
@@ -133,8 +129,10 @@ def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
133129
pass
134130
elif isinstance(match.obj, Sequence):
135131
try:
132+
# TODO: canonical concrete path normalizes negative index
133+
# to positive.
136134
yield JSONPathMatch(
137-
path=match.path + self.path,
135+
path=match.path + f"[{self.index}]",
138136
obj=self.env.getitem(match.obj, self.index),
139137
root=match.root,
140138
filter_context=match.filter_context(),
@@ -151,7 +149,7 @@ async def resolve_async(
151149
# Try the string representation of the index as a key.
152150
try:
153151
yield JSONPathMatch(
154-
path=f'{match.path}["{self.index}"]',
152+
path=f"{match.path}['{self.index}']",
155153
obj=await self.env.getitem_async(match.obj, self._as_key),
156154
root=match.root,
157155
filter_context=match.filter_context(),
@@ -161,7 +159,7 @@ async def resolve_async(
161159
elif isinstance(match.obj, Sequence):
162160
try:
163161
yield JSONPathMatch(
164-
path=match.path + self.path,
162+
path=match.path + f"[{self.index}]",
165163
obj=await self.env.getitem_async(match.obj, self.index),
166164
root=match.root,
167165
filter_context=match.filter_context(),
@@ -201,6 +199,7 @@ def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
201199
idx = self.slice.start or 0
202200
step = self.slice.step or 1
203201
for obj in self.env.getitem(match.obj, self.slice):
202+
# TODO: canonical concrete index
204203
yield JSONPathMatch(
205204
path=f"{match.path}[{idx}]",
206205
obj=obj,
@@ -233,16 +232,7 @@ class WildSelector(JSONPathSelector):
233232
"""Wildcard expansion selector."""
234233

235234
def __str__(self) -> str:
236-
return ".*"
237-
238-
def _path(self, key: object) -> str:
239-
"""Return a string representation of an object property key."""
240-
if not isinstance(key, str):
241-
key = str(key)
242-
243-
if self.env.re_key.match(key):
244-
return f".{key}"
245-
return f'["{key}"]'
235+
return "[*]"
246236

247237
def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
248238
for match in matches:
@@ -251,7 +241,7 @@ def resolve(self, matches: Iterable[JSONPathMatch]) -> Iterable[JSONPathMatch]:
251241
if isinstance(match.obj, Mapping):
252242
for key, val in match.obj.items():
253243
yield JSONPathMatch(
254-
path=match.path + self._path(key),
244+
path=match.path + f"['{key}']",
255245
obj=val,
256246
root=match.root,
257247
filter_context=match.filter_context(),
@@ -273,7 +263,7 @@ async def resolve_async(
273263
if isinstance(match.obj, Mapping):
274264
for key, val in match.obj.items():
275265
yield JSONPathMatch(
276-
path=match.path + self._path(key),
266+
path=match.path + f"['{key}']",
277267
obj=val,
278268
root=match.root,
279269
filter_context=match.filter_context(),
@@ -294,23 +284,14 @@ class RecursiveDescentSelector(JSONPathSelector):
294284
def __str__(self) -> str:
295285
return ".."
296286

297-
def _path(self, key: object) -> str:
298-
"""Return a string representation of an object property key."""
299-
if not isinstance(key, str):
300-
key = str(key)
301-
302-
if self.env.re_key.match(key):
303-
return f".{key}"
304-
return f'["{key}"]'
305-
306287
def _expand(self, match: JSONPathMatch) -> Iterable[JSONPathMatch]:
307288
if isinstance(match.obj, Mapping):
308289
for key, val in match.obj.items():
309290
if isinstance(val, str):
310291
pass
311292
elif isinstance(val, (Mapping, Sequence)):
312293
_match = JSONPathMatch(
313-
path=match.path + self._path(key),
294+
path=match.path + f"['{key}']",
314295
obj=val,
315296
root=match.root,
316297
filter_context=match.filter_context(),
@@ -378,7 +359,7 @@ def __str__(self) -> str:
378359
step = item.slice.step if item.slice.step is not None else "1"
379360
buf.append(f"{start}:{stop}:{step}")
380361
elif isinstance(item, PropertySelector):
381-
buf.append(item.name)
362+
buf.append(f"'{item.name}'")
382363
else:
383364
buf.append(str(item.index))
384365
return f"[{', '.join(buf)}]"

‎tests/test_ietf.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,8 @@ class Case:
134134
data=["a", "b", "c", "d", "e", "f", "g"],
135135
want=["g", "f", "e", "d", "c", "b", "a"],
136136
),
137+
# TODO: Filter selector examples
138+
# TODO: child segment examples
137139
]
138140

139141

‎tests/test_parse.py‎

Lines changed: 37 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -18,27 +18,31 @@ class Case:
1818
Case(description="empty", path="", want="$"),
1919
Case(description="just root", path="$", want="$"),
2020
Case(description="root dot", path="$.", want="$"),
21-
Case(description="implicit root dot property", path=".thing", want="$.thing"),
22-
Case(description="root dot property", path="$.thing", want="$.thing"),
23-
Case(description="root bracket property", path="$[thing]", want="$.thing"),
24-
Case(description="root double quoted property", path='$["thing"]', want="$.thing"),
25-
Case(description="root single quoted property", path="$['thing']", want="$.thing"),
21+
Case(description="implicit root dot property", path=".thing", want="$['thing']"),
22+
Case(description="root dot property", path="$.thing", want="$['thing']"),
23+
Case(description="root bracket property", path="$[thing]", want="$['thing']"),
24+
Case(
25+
description="root double quoted property", path='$["thing"]', want="$['thing']"
26+
),
27+
Case(
28+
description="root single quoted property", path="$['thing']", want="$['thing']"
29+
),
2630
Case(
2731
description="root quoted property with non-ident chars",
2832
path="$['anything{!%']",
29-
want='$["anything{!%"]',
33+
want="$['anything{!%']",
3034
),
31-
Case(description="root dot bracket property", path="$.[thing]", want="$.thing"),
35+
Case(description="root dot bracket property", path="$.[thing]", want="$['thing']"),
3236
Case(description="root dot index", path="$.1", want="$[1]"),
3337
Case(description="root bracket index", path="$[1]", want="$[1]"),
3438
Case(description="root slice", path="$[1:-1]", want="$[1:-1:1]"),
3539
Case(description="root dot slice", path="$.[1:-1]", want="$[1:-1:1]"),
3640
Case(description="root slice with step", path="$[1:-1:2]", want="$[1:-1:2]"),
3741
Case(description="root slice with empty start", path="$[:-1]", want="$[:-1:1]"),
3842
Case(description="root slice with empty stop", path="$[1:]", want="$[1::1]"),
39-
Case(description="root dot wild", path="$.*", want="$.*"),
40-
Case(description="root bracket wild", path="$[*]", want="$.*"),
41-
Case(description="root dot bracket wild", path="$.[*]", want="$.*"),
43+
Case(description="root dot wild", path="$.*", want="$[*]"),
44+
Case(description="root bracket wild", path="$[*]", want="$[*]"),
45+
Case(description="root dot bracket wild", path="$.[*]", want="$[*]"),
4246
Case(description="root descend", path="$..", want="$.."),
4347
Case(description="root dot descend", path="$...", want="$.."),
4448
Case(description="root selector list", path="$[1,2]", want="$[1, 2]"),
@@ -51,117 +55,117 @@ class Case:
5155
Case(
5256
description="root selector list with properties",
5357
path="$[some,thing]",
54-
want="$[some, thing]",
58+
want="$['some', 'thing']",
5559
),
5660
Case(
5761
description="root selector list with quoted properties",
5862
path="$[\"some\",'thing']",
59-
want="$[some, thing]",
63+
want="$['some', 'thing']",
6064
),
6165
Case(
6266
description="implicit root selector list with mixed selectors",
6367
path='$["some",thing, 1, 2:-2:2]',
64-
want="$[some, thing, 1, 2:-2:2]",
68+
want="$['some', 'thing', 1, 2:-2:2]",
6569
),
6670
Case(
6771
description="filter self dot property",
6872
path="[?(@.thing)]",
69-
want="$[?(@.thing)]",
73+
want="$[?(@['thing'])]",
7074
),
7175
Case(
7276
description="filter root dot property",
7377
path="$.some[?($.thing)]",
74-
want="$.some[?($.thing)]",
78+
want="$['some'][?($['thing'])]",
7579
),
7680
Case(
7781
description="filter with equality test",
7882
path="$.some[?(@.thing == 7)]",
79-
want="$.some[?(@.thing == 7)]",
83+
want="$['some'][?(@['thing'] == 7)]",
8084
),
8185
Case(
8286
description="filter with >=",
8387
path="$.some[?(@.thing >= 7)]",
84-
want="$.some[?(@.thing >= 7)]",
88+
want="$['some'][?(@['thing'] >= 7)]",
8589
),
8690
Case(
8791
description="filter with >=",
8892
path="$.some[?(@.thing >= 7)]",
89-
want="$.some[?(@.thing >= 7)]",
93+
want="$['some'][?(@['thing'] >= 7)]",
9094
),
9195
Case(
9296
description="filter with !=",
9397
path="$.some[?(@.thing != 7)]",
94-
want="$.some[?(@.thing != 7)]",
98+
want="$['some'][?(@['thing'] != 7)]",
9599
),
96100
Case(
97101
description="filter with <>",
98102
path="$.some[?(@.thing != 7)]",
99-
want="$.some[?(@.thing != 7)]",
103+
want="$['some'][?(@['thing'] != 7)]",
100104
),
101105
Case(
102106
description="filter with regex",
103107
path="$.some[?(@.thing =~ /(foo|bar)/i)]",
104-
want="$.some[?(@.thing =~ /(foo|bar)/i)]",
108+
want="$['some'][?(@['thing'] =~ /(foo|bar)/i)]",
105109
),
106110
Case(
107111
description="filter with list membership test",
108112
path="$.some[?(@.thing in ['foo', 'bar', 42])]",
109-
want="$.some[?(@.thing in ['foo', 'bar', 42])]",
113+
want="$['some'][?(@['thing'] in ['foo', 'bar', 42])]",
110114
),
111115
Case(
112116
description="filter with boolean literals",
113117
path="$.some[?(true == false)]",
114-
want="$.some[?(True == False)]",
118+
want="$['some'][?(true == false)]",
115119
),
116120
Case(
117121
description="filter with nil literal",
118122
path="$.some[?(@.thing == nil)]",
119-
want="$.some[?(@.thing == nil)]",
123+
want="$['some'][?(@['thing'] == nil)]",
120124
),
121125
Case(
122126
description="null is the same as nil",
123127
path="$.some[?(@.thing == null)]",
124-
want="$.some[?(@.thing == nil)]",
128+
want="$['some'][?(@['thing'] == nil)]",
125129
),
126130
Case(
127131
description="none is the same as nil",
128132
path="$.some[?(@.thing == none)]",
129-
want="$.some[?(@.thing == nil)]",
133+
want="$['some'][?(@['thing'] == nil)]",
130134
),
131135
Case(
132136
description="filter with test for undefined",
133137
path="$.some[?(@.thing == undefined)]",
134-
want="$.some[?(@.thing == undefined)]",
138+
want="$['some'][?(@['thing'] == undefined)]",
135139
),
136140
Case(
137141
description="missing is the same as undefined",
138142
path="$.some[?(@.thing == missing)]",
139-
want="$.some[?(@.thing == undefined)]",
143+
want="$['some'][?(@['thing'] == undefined)]",
140144
),
141145
Case(
142146
description="filter with string literal",
143147
path="$.some[?(@.thing == 'foo')]",
144-
want="$.some[?(@.thing == 'foo')]",
148+
want="$['some'][?(@['thing'] == 'foo')]",
145149
),
146150
Case(
147151
description="filter with integer literal",
148152
path="$.some[?(@.thing == 1)]",
149-
want="$.some[?(@.thing == 1)]",
153+
want="$['some'][?(@['thing'] == 1)]",
150154
),
151155
Case(
152156
description="filter with float literal",
153157
path="$.some[?(@.thing == 1.1)]",
154-
want="$.some[?(@.thing == 1.1)]",
158+
want="$['some'][?(@['thing'] == 1.1)]",
155159
),
156160
Case(
157161
description="filter with logical not",
158162
path="$.some[?(@.thing > 1 and not $.other)]",
159-
want="$.some[?(@.thing > 1 and not $.other)]",
163+
want="$['some'][?(@['thing'] > 1 and not $['other'])]",
160164
),
161165
Case(
162166
description="filter with grouped expression",
163167
path="$.some[?(@.thing > 1 and ($.foo or $.bar))]",
164-
want="$.some[?(@.thing > 1 and $.foo or $.bar)]",
168+
want="$['some'][?(@['thing'] > 1 and $['foo'] or $['bar'])]",
165169
),
166170
]
167171

0 commit comments

Comments
 (0)