Skip to content

Commit dd3b642

Browse files
committed
Fix JSON Pointer regression
1 parent 9dd1480 commit dd3b642

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

jsonpath/pointer.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,20 @@ def _handle_key_error(self, obj: Any, key: str, err: Exception) -> object:
166166
):
167167
return key[1:]
168168

169+
# Handle dictionaries with integer or float keys. Note that JSON objects must
170+
# have string keys. We are supporting this for historical reasons.
171+
if isinstance(obj, Mapping):
172+
try:
173+
_key: Union[int, float] = int(key)
174+
except ValueError:
175+
try:
176+
_key = float(key)
177+
except ValueError:
178+
raise JSONPointerKeyError(key) from err
179+
180+
if _key in obj:
181+
return obj[_key]
182+
169183
raise JSONPointerKeyError(key) from err
170184

171185
def _handle_type_error(self, obj: Any, key: str, err: Exception) -> object:

tests/test_json_pointer.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,3 +329,17 @@ def test_index_like_token_on_object_value() -> None:
329329
data = {"foo": {"-1": "bar"}}
330330
pointer = JSONPointer("/foo/-1")
331331
assert pointer.resolve(data) == "bar"
332+
333+
334+
def test_dictionary_with_int_key() -> None:
335+
# JSON object keys must be strings, but Python dicts can have integer keys.
336+
data = {"foo": {1: "bar"}}
337+
pointer = JSONPointer("/foo/1")
338+
assert pointer.resolve(data) == "bar"
339+
340+
341+
def test_dictionary_with_float_key() -> None:
342+
# JSON object keys must be strings, but Python dicts can have float keys.
343+
data = {"foo": {1.1: "bar"}}
344+
pointer = JSONPointer("/foo/1.1")
345+
assert pointer.resolve(data) == "bar"

0 commit comments

Comments
 (0)