Skip to content

Commit

Permalink
feat: JSONPointer.exists(), closes #19
Browse files Browse the repository at this point in the history
  • Loading branch information
jg-rp committed Jul 17, 2023
1 parent 65d9c94 commit cf97fec
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- Added a command line interface, exposing JSONPath, JSON Pointer and JSON Patch features.
- Added `JSONPointer.parent()`, a method that returns a the parent of the pointer, as a new `JSONPointer`.
- Implemented `JSONPointer.__truediv__()` to allow creation of child pointers from an existing pointer.
- Added `JSONPointer.exists()`, a method that returns `True` if a the pointer can be resolved against some data, or `False` otherwise.

## Version 0.8.1

Expand Down
26 changes: 26 additions & 0 deletions jsonpath/pointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,9 @@ def from_parts(
before parsing the pointer.
uri_decode: If `True`, the pointer will be unescaped using _urllib_
before being parsed.
Returns:
A new `JSONPointer` built from _parts_.
"""
_parts = (str(p) for p in parts)
if uri_decode:
Expand Down Expand Up @@ -317,6 +320,29 @@ def __eq__(self, other: object) -> bool:
def __repr__(self) -> str:
return f"JSONPointer({self._s!r})"

def exists(
self, data: Union[str, IOBase, Sequence[object], Mapping[str, object]]
) -> bool:
"""Return _True_ if this pointer can be resolved against _data_.
Note that `JSONPointer.resolve()` can return legitimate falsy values
that form part of the target JSON document. This method will return
`True` if a falsy value is found.
Args:
data: The target JSON "document" or equivalent Python objects.
Returns:
_True_ if this pointer can be resolved against _data_, or _False_
otherwise.
"""
try:
self.resolve(data)
except JSONPointerResolutionError:
return False
return True

def parent(self) -> JSONPointer:
"""Return this pointer's parent, as a new `JSONPointer`.
Expand Down
7 changes: 7 additions & 0 deletions tests/test_json_pointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,10 @@ def test_join_pointers() -> None:

with pytest.raises(TypeError):
pointer / 0


def test_pointer_exists() -> None:
data = {"some": {"thing": [1, 2, 3]}, "other": None}
assert JSONPointer("/some/thing").exists(data) is True
assert JSONPointer("/other").exists(data) is True
assert JSONPointer("/nosuchthing").exists(data) is False

0 comments on commit cf97fec

Please sign in to comment.