Skip to content

Commit 850dc8a

Browse files
committed
Resolve JSON Pointers with jsonpath.resolve().
1 parent 43029ae commit 850dc8a

6 files changed

Lines changed: 139 additions & 13 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
**Features**
1010

1111
- Added the `JSONPointer` class and methods for converting a `JSONPathMatch` to a `JSONPointer`.
12+
- Added `jsonpath.resolve()`, a convenience function for resolving a [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901).
1213
- All selectors now use `env.match_class` to instantiate new `JSONPathMatch` objects. This allows for subclassing of `JSONPathMatch`.
1314

1415
## Version 0.7.1

‎docs/api.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# API Reference
2-
32
::: jsonpath.JSONPathEnvironment
43
handler: python
54

@@ -13,4 +12,4 @@
1312
handler: python
1413

1514
::: jsonpath.JSONPointer
16-
handler: python
15+
handler: python

‎docs/quickstart.md‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,62 @@ some_users = path.findall(some_data)
133133
other_users = path.findall(other_data)
134134
```
135135

136+
## `resolve(pointer, data)`
137+
138+
Resolve a [JSON Pointer](https://datatracker.ietf.org/doc/html/rfc6901). A JSON Pointer references a single object on a specific "path" in a JSON document. Here, _pointer_ must be a string representation of a JSON Pointer and _data_ can be a file-like object or string containing JSON formatted data, or equivalent Python objects.
139+
140+
```python
141+
import jsonpath
142+
143+
data = {
144+
"users": [
145+
{
146+
"name": "Sue",
147+
"score": 100,
148+
},
149+
{
150+
"name": "John",
151+
"score": 86,
152+
},
153+
{
154+
"name": "Sally",
155+
"score": 84,
156+
},
157+
{
158+
"name": "Jane",
159+
"score": 55,
160+
},
161+
]
162+
}
163+
164+
sue_score = jsonpath.resolve("/users/0/score", data)
165+
print(sue_score) # 100
166+
```
167+
168+
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`.
169+
170+
```python
171+
import jsonpath
172+
173+
data = {
174+
"users": [
175+
{
176+
"name": "Sue",
177+
"score": 100,
178+
},
179+
{
180+
"name": "John",
181+
"score": 86,
182+
},
183+
]
184+
}
185+
186+
sue_score = jsonpath.resolve("/users/99/score", data, default=0)
187+
print(sue_score) # 0
188+
```
189+
190+
See also [`JSONPathMatch.pointer()`](api.md#jsonpath.match.JSONPathMatch.pointer), which builds a [`JSONPointer`](api.md#jsonpath.JSONPointer) from a `JSONPathMatch`.
191+
136192
## What's Next?
137193

138194
Read about user-defined filter functions at [Function Extensions](advanced.md#function-extensions), or see how to make extra data available to filters with [Extra Filter Context](advanced.md#extra-filter-context).

‎jsonpath/__init__.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,17 @@
1010
from .exceptions import JSONPathTypeError
1111
from .exceptions import JSONPointerError
1212
from .exceptions import JSONPointerIndexError
13+
from .exceptions import JSONPointerKeyError
14+
from .exceptions import JSONPointerResolutionError
15+
from .exceptions import JSONPointerTypeError
1316
from .filter import UNDEFINED
1417
from .lex import Lexer
1518
from .match import JSONPathMatch
1619
from .parse import Parser
1720
from .path import CompoundJSONPath
1821
from .path import JSONPath
1922
from .pointer import JSONPointer
23+
from .pointer import resolve
2024

2125
__all__ = (
2226
"compile",
@@ -36,8 +40,12 @@
3640
"JSONPointer",
3741
"JSONPointerError",
3842
"JSONPointerIndexError",
43+
"JSONPointerKeyError",
44+
"JSONPointerResolutionError",
45+
"JSONPointerTypeError",
3946
"Lexer",
4047
"Parser",
48+
"resolve",
4149
"UNDEFINED",
4250
)
4351

‎jsonpath/pointer.py‎

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
from .exceptions import JSONPointerIndexError
1818
from .exceptions import JSONPointerKeyError
19+
from .exceptions import JSONPointerResolutionError
1920
from .exceptions import JSONPointerTypeError
2021

2122
if TYPE_CHECKING:
@@ -132,6 +133,8 @@ def _getitem(self, obj: Any, key: Any) -> Any:
132133
except ValueError:
133134
pass
134135
raise JSONPointerTypeError(str(err)) from err
136+
except IndexError as err:
137+
raise JSONPointerIndexError(str(err)) from err
135138

136139
def resolve(
137140
self, data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]
@@ -147,10 +150,10 @@ def resolve(
147150
Raises:
148151
JSONPointerIndexError: When attempting to access a sequence by
149152
and out of range index.
150-
JSONPointerKeyError: If any mapping object along the path does not contain
151-
a specified key.
152-
JSONPointerTypeError: When attempting to resolve a non-index string path
153-
part against a sequence.
153+
JSONPointerKeyError: If any mapping object along the path does not
154+
contain a specified key.
155+
JSONPointerTypeError: When attempting to resolve a non-index string
156+
path part against a sequence.
154157
"""
155158
if isinstance(data, str):
156159
data = json.loads(data)
@@ -167,17 +170,19 @@ def resolve_parent(
167170
data: The target JSON "document" or equivalent Python objects.
168171
169172
Returns:
170-
A (parent, object) tuple, where parent will be `None` if this pointer
171-
points to the root node in the document. If the parent exists but the
172-
last object does not, (parent, None) will be returned.
173+
A `(parent, object)` tuple, where parent will be `None` if this
174+
pointer points to the root node in the document. If the parent
175+
exists but the last object does not, `(parent, None)` will be
176+
returned.
173177
174178
Raises:
175179
JSONPointerIndexError: When attempting to access a sequence by
176180
and out of range index, unless using the special `-` index.
177-
JSONPointerKeyError: If any mapping object along the path does not contain
178-
a specified key, unless it is the last part of the pointer.
179-
JSONPointerTypeError: When attempting to resolve a non-index string path
180-
part against a sequence.
181+
JSONPointerKeyError: If any mapping object along the path does not
182+
contain a specified key, unless it is the last part of the
183+
pointer.
184+
JSONPointerTypeError: When attempting to resolve a non-index string
185+
path part against a sequence.
181186
"""
182187
if not len(self.parts):
183188
return (None, self.resolve(data))
@@ -212,3 +217,46 @@ def from_match(
212217
unicode_escape=False,
213218
uri_decode=False,
214219
)
220+
221+
222+
_missing = object()
223+
224+
225+
def resolve(
226+
pointer: str,
227+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
228+
*,
229+
default: object = _missing,
230+
unicode_escape: bool = True,
231+
uri_decode: bool = False,
232+
) -> object:
233+
"""Resolve JSON Pointer _pointer_ against _data_.
234+
235+
Args:
236+
pointer: A string representation of a JSON Pointer.
237+
data: The target JSON "document" or equivalent Python objects.
238+
default: A default value to return if the pointer can't be resolved.
239+
unicode_escape: If `True`, UTF-16 escape sequences will be decoded
240+
before parsing the pointer.
241+
uri_decode: If `True`, the pointer will be unescaped using _urllib_
242+
before being parsed.
243+
244+
Returns:
245+
The object in _data_ pointed to by this pointer.
246+
247+
Raises:
248+
JSONPointerIndexError: When attempting to access a sequence by
249+
and out of range index.
250+
JSONPointerKeyError: If any mapping object along the path does not contain
251+
a specified key.
252+
JSONPointerTypeError: When attempting to resolve a non-index string path
253+
part against a sequence.
254+
"""
255+
try:
256+
return JSONPointer(
257+
pointer, unicode_escape=unicode_escape, uri_decode=uri_decode
258+
).resolve(data)
259+
except JSONPointerResolutionError:
260+
if default is not _missing:
261+
return default
262+
raise

‎tests/test_json_pointer.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import jsonpath
77
from jsonpath import JSONPointer
88
from jsonpath import JSONPointerIndexError
9+
from jsonpath import JSONPointerResolutionError
910

1011

1112
def test_match_to_pointer() -> None:
@@ -125,3 +126,16 @@ def test_resolve_from_file_like() -> None:
125126
assert pointer.resolve(data) == [1, 2, 3]
126127
data.seek(0)
127128
assert pointer.resolve_parent(data) == ({"thing": [1, 2, 3]}, [1, 2, 3])
129+
130+
131+
def test_convenience_resolve() -> None:
132+
data = {"some": {"thing": [1, 2, 3]}}
133+
assert jsonpath.resolve("/some/thing/0", data) == 1
134+
135+
with pytest.raises(JSONPointerResolutionError):
136+
jsonpath.resolve("/some/thing/99", data)
137+
138+
139+
def test_convenience_resolve_default() -> None:
140+
data = {"some": {"thing": [1, 2, 3]}}
141+
assert jsonpath.resolve("/some/thing/99", data, default=0) == 0

0 commit comments

Comments
 (0)