Skip to content

Commit 43029ae

Browse files
committed
Use IOBase for file-like checks.
1 parent 0100020 commit 43029ae

4 files changed

Lines changed: 82 additions & 41 deletions

File tree

‎jsonpath/env.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from typing import Mapping
1515
from typing import Optional
1616
from typing import Sequence
17-
from typing import TextIO
1817
from typing import Type
1918
from typing import Union
2019

@@ -36,6 +35,8 @@
3635
from .token import Token
3736

3837
if TYPE_CHECKING:
38+
from io import IOBase
39+
3940
from .match import FilterContextVars
4041

4142

@@ -175,7 +176,7 @@ def compile(self, path: str) -> Union[JSONPath, CompoundJSONPath]: # noqa: A003
175176
def findall(
176177
self,
177178
path: str,
178-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
179+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
179180
*,
180181
filter_context: Optional[FilterContextVars] = None,
181182
) -> List[object]:
@@ -203,7 +204,7 @@ def findall(
203204
def finditer(
204205
self,
205206
path: str,
206-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
207+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
207208
*,
208209
filter_context: Optional[FilterContextVars] = None,
209210
) -> Iterable[JSONPathMatch]:
@@ -229,7 +230,7 @@ def finditer(
229230
async def findall_async(
230231
self,
231232
path: str,
232-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
233+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
233234
*,
234235
filter_context: Optional[FilterContextVars] = None,
235236
) -> List[object]:
@@ -241,7 +242,7 @@ async def findall_async(
241242
async def finditer_async(
242243
self,
243244
path: str,
244-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
245+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
245246
*,
246247
filter_context: Optional[FilterContextVars] = None,
247248
) -> AsyncIterable[JSONPathMatch]:

‎jsonpath/path.py‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import itertools
55
import json
6+
from io import IOBase
67
from typing import TYPE_CHECKING
78
from typing import Any
89
from typing import AsyncIterable
@@ -11,7 +12,6 @@
1112
from typing import Mapping
1213
from typing import Optional
1314
from typing import Sequence
14-
from typing import TextIO
1515
from typing import Tuple
1616
from typing import TypeVar
1717
from typing import Union
@@ -51,7 +51,7 @@ def __str__(self) -> str:
5151

5252
def findall(
5353
self,
54-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
54+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
5555
*,
5656
filter_context: Optional[FilterContextVars] = None,
5757
) -> List[object]:
@@ -77,7 +77,7 @@ def findall(
7777
"""
7878
if isinstance(data, str):
7979
_data = json.loads(data)
80-
elif isinstance(data, TextIO):
80+
elif isinstance(data, IOBase):
8181
_data = json.loads(data.read())
8282
else:
8383
_data = data
@@ -87,7 +87,7 @@ def findall(
8787

8888
def finditer(
8989
self,
90-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
90+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
9191
*,
9292
filter_context: Optional[FilterContextVars] = None,
9393
) -> Iterable[JSONPathMatch]:
@@ -112,7 +112,7 @@ def finditer(
112112
"""
113113
if isinstance(data, str):
114114
_data = json.loads(data)
115-
elif isinstance(data, TextIO):
115+
elif isinstance(data, IOBase):
116116
_data = json.loads(data.read())
117117
else:
118118
_data = data
@@ -135,14 +135,14 @@ def finditer(
135135

136136
async def findall_async(
137137
self,
138-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
138+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
139139
*,
140140
filter_context: Optional[FilterContextVars] = None,
141141
) -> List[object]:
142142
"""An async version of `findall()`."""
143143
if isinstance(data, str):
144144
_data = json.loads(data)
145-
elif isinstance(data, TextIO):
145+
elif isinstance(data, IOBase):
146146
_data = json.loads(data.read())
147147
else:
148148
_data = data
@@ -155,14 +155,14 @@ async def findall_async(
155155

156156
async def finditer_async(
157157
self,
158-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
158+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
159159
*,
160160
filter_context: Optional[FilterContextVars] = None,
161161
) -> AsyncIterable[JSONPathMatch]:
162162
"""An async version of `finditer()`."""
163163
if isinstance(data, str):
164164
_data = json.loads(data)
165-
elif isinstance(data, TextIO):
165+
elif isinstance(data, IOBase):
166166
_data = json.loads(data.read())
167167
else:
168168
_data = data
@@ -213,7 +213,7 @@ def __str__(self) -> str:
213213

214214
def findall(
215215
self,
216-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
216+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
217217
filter_context: Optional[FilterContextVars] = None,
218218
) -> List[object]:
219219
"""Find all objects in `data` matching the given JSONPath `path`.
@@ -250,7 +250,7 @@ def findall(
250250

251251
def finditer(
252252
self,
253-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
253+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
254254
filter_context: Optional[FilterContextVars] = None,
255255
) -> Iterable[JSONPathMatch]:
256256
"""Generate `JSONPathMatch` objects for each match.
@@ -287,7 +287,7 @@ def finditer(
287287

288288
async def findall_async(
289289
self,
290-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
290+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
291291
filter_context: Optional[FilterContextVars] = None,
292292
) -> List[object]:
293293
"""An async version of `findall()`."""
@@ -305,7 +305,7 @@ async def findall_async(
305305

306306
async def finditer_async(
307307
self,
308-
data: Union[str, TextIO, Sequence[Any], Mapping[str, Any]],
308+
data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]],
309309
filter_context: Optional[FilterContextVars] = None,
310310
) -> AsyncIterable[JSONPathMatch]:
311311
"""An async version of `finditer()`."""

‎jsonpath/pointer.py‎

Lines changed: 43 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
from __future__ import annotations
33

44
import codecs
5+
import json
56
from functools import reduce
7+
from io import IOBase
68
from operator import getitem
79
from typing import TYPE_CHECKING
810
from typing import Any
@@ -14,7 +16,6 @@
1416

1517
from .exceptions import JSONPointerIndexError
1618
from .exceptions import JSONPointerKeyError
17-
from .exceptions import JSONPointerResolutionError
1819
from .exceptions import JSONPointerTypeError
1920

2021
if TYPE_CHECKING:
@@ -132,45 +133,67 @@ def _getitem(self, obj: Any, key: Any) -> Any:
132133
pass
133134
raise JSONPointerTypeError(str(err)) from err
134135

135-
# TODO: handle JSON "document" string and TextIO
136-
137-
def resolve(self, obj: Union[Sequence[Any], Mapping[str, Any]]) -> object:
138-
"""Resolve this pointer against _obj_.
136+
def resolve(
137+
self, data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]
138+
) -> object:
139+
"""Resolve this pointer against _data_.
139140
140141
Args:
141-
obj: The target JSON "document" or equivalent Python objects.
142+
data: The target JSON "document" or equivalent Python objects.
142143
143144
Returns:
144-
The object in _obj_ pointed to by this pointer.
145+
The object in _data_ pointed to by this pointer.
145146
146147
Raises:
147148
JSONPointerIndexError: When attempting to access a sequence by
148149
and out of range index.
149-
KeyError: If any mapping object along the path does not contain
150+
JSONPointerKeyError: If any mapping object along the path does not contain
150151
a specified key.
151-
TypeError: When attempting to resolve a non-index string path part
152-
against a sequence.
152+
JSONPointerTypeError: When attempting to resolve a non-index string path
153+
part against a sequence.
153154
"""
154-
return reduce(self._getitem, self.parts, obj)
155-
156-
def resolve_with_parent(
157-
self, obj: Union[Sequence[Any], Mapping[str, Any]]
155+
if isinstance(data, str):
156+
data = json.loads(data)
157+
elif isinstance(data, IOBase):
158+
data = json.loads(data.read())
159+
return reduce(self._getitem, self.parts, data)
160+
161+
def resolve_parent(
162+
self, data: Union[str, IOBase, Sequence[Any], Mapping[str, Any]]
158163
) -> Tuple[Union[Sequence[Any], Mapping[str, Any], None], object]:
159-
"""Resolve this pointer against _obj_, include the result's parent object.
164+
"""Resolve this pointer against _data_, return the object and its parent.
160165
161166
Args:
162-
obj: The target JSON "document" or equivalent Python objects.
167+
data: The target JSON "document" or equivalent Python objects.
163168
164169
Returns:
165170
A (parent, object) tuple, where parent will be `None` if this pointer
166-
points to the root node in the document.
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+
174+
Raises:
175+
JSONPointerIndexError: When attempting to access a sequence by
176+
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.
167181
"""
168182
if not len(self.parts):
169-
return (None, self.resolve(obj))
170-
parent = reduce(self._getitem, self.parts[:-1], obj)
183+
return (None, self.resolve(data))
184+
185+
if isinstance(data, str):
186+
_data = json.loads(data)
187+
elif isinstance(data, IOBase):
188+
_data = json.loads(data.read())
189+
else:
190+
_data = data
191+
192+
parent = reduce(self._getitem, self.parts[:-1], _data)
193+
171194
try:
172195
return (parent, self._getitem(parent, self.parts[-1]))
173-
except JSONPointerResolutionError:
196+
except (JSONPointerIndexError, JSONPointerKeyError):
174197
return (parent, None)
175198

176199
@classmethod

‎tests/test_json_pointer.py‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
"""JSONPointer test cases."""
2+
from io import StringIO
3+
24
import pytest
35

46
import jsonpath
@@ -89,22 +91,37 @@ def test_hyphen_index() -> None:
8991
def test_resolve_with_parent() -> None:
9092
data = {"some": {"thing": [1, 2, 3]}}
9193
pointer = JSONPointer("/some/thing")
92-
parent, rv = pointer.resolve_with_parent(data)
94+
parent, rv = pointer.resolve_parent(data)
9395
assert parent == data["some"]
9496
assert rv == data["some"]["thing"]
9597

9698

9799
def test_resolve_with_missing_parent() -> None:
98100
data = {"some": {"thing": [1, 2, 3]}}
99101
pointer = JSONPointer("")
100-
parent, rv = pointer.resolve_with_parent(data)
102+
parent, rv = pointer.resolve_parent(data)
101103
assert parent is None
102104
assert rv == data
103105

104106

105107
def test_resolve_with_missing_target() -> None:
106108
data = {"some": {"thing": [1, 2, 3]}}
107109
pointer = JSONPointer("some/other")
108-
parent, rv = pointer.resolve_with_parent(data)
110+
parent, rv = pointer.resolve_parent(data)
109111
assert parent == data
110112
assert rv is None
113+
114+
115+
def test_resolve_from_json_string() -> None:
116+
data = r'{"some": {"thing": [1,2,3]}}'
117+
pointer = JSONPointer("/some/thing")
118+
assert pointer.resolve(data) == [1, 2, 3]
119+
assert pointer.resolve_parent(data) == ({"thing": [1, 2, 3]}, [1, 2, 3])
120+
121+
122+
def test_resolve_from_file_like() -> None:
123+
data = StringIO(r'{"some": {"thing": [1,2,3]}}')
124+
pointer = JSONPointer("/some/thing")
125+
assert pointer.resolve(data) == [1, 2, 3]
126+
data.seek(0)
127+
assert pointer.resolve_parent(data) == ({"thing": [1, 2, 3]}, [1, 2, 3])

0 commit comments

Comments
 (0)