Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions doc/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,21 @@ same path on several objects.
>>> obj2 = {'foo': {'0': 1, '1': 10, '2': 100}}
>>> pointer.resolve(obj2)
10

Checking pointer prefixes
-------------------------

``child.contains(parent)`` checks whether the parent's parts are a prefix of
the child's parts. The equivalent membership expression is ``parent in child``.
The comparison is between whole path parts, so ``/foo/b`` is not a prefix of
``/foo/bar``. Equal pointers and the root pointer are prefixes too:

>>> from jsonpointer import JsonPointer
>>> parent = JsonPointer('/foo')
>>> child = JsonPointer('/foo/bar')
>>> child.contains(parent)
True
>>> parent in child
True
>>> child in parent
False
27 changes: 25 additions & 2 deletions jsonpointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,11 +349,34 @@ def walk(self, doc, part):
raise JsonPointerException("member '%s' not found" % (part,))

def contains(self, ptr):
""" Returns True if self contains the given ptr """
"""Returns True if ptr's parts are a prefix of this pointer's parts.

Equal pointers and the root pointer are also prefixes. For example,
the longer pointer calls contains() with its parent:

>>> child = JsonPointer('/foo/bar')
>>> parent = JsonPointer('/foo')
>>> child.contains(parent)
True
>>> parent.contains(child)
False
>>> child.contains(child)
True
>>> child.contains(JsonPointer(''))
True
>>> child.contains(JsonPointer('/foo/b'))
False
"""
return self.parts[:len(ptr.parts)] == ptr.parts

def __contains__(self, item):
""" Returns True if self contains the given ptr """
"""Equivalent to contains(): item must be a prefix of self.

>>> JsonPointer('/foo') in JsonPointer('/foo/bar')
True
>>> JsonPointer('/foo/bar') in JsonPointer('/foo')
False
"""
return self.contains(item)

def join(self, suffix):
Expand Down
Loading