diff options
author | Stefan Kögl <stefan@skoegl.net> | 2012-11-15 11:08:01 +0100 |
---|---|---|
committer | Stefan Kögl <stefan@skoegl.net> | 2012-11-15 11:08:29 +0100 |
commit | 1e818af78ec962d6b351f3de89d771dfa86a7368 (patch) | |
tree | fa647fb8b1be5a54d0a881245fcb84d2704a3a55 | |
parent | 164a9151480d5e84bd1146f723ab5b8c8b5063a3 (diff) | |
download | python-json-pointer-1e818af78ec962d6b351f3de89d771dfa86a7368.tar.gz |
add JsonPointer.to_last() for use in jsonpatch
-rw-r--r-- | jsonpointer.py | 35 |
1 files changed, 30 insertions, 5 deletions
diff --git a/jsonpointer.py b/jsonpointer.py index 3a86773..fe3cecf 100644 --- a/jsonpointer.py +++ b/jsonpointer.py @@ -146,6 +146,14 @@ class JsonPointer(object): self.parts = parts + def to_last(self, doc, default=_nothing): + """ Resolves ptr until the last step, returns (sub-doc, last-step) """ + + for part in self.parts[:-1]: + doc = self.walk(doc, part) + + return doc, self.get_part(doc, self.parts[-1]) + def resolve(self, doc, default=_nothing): """Resolves the pointer against doc and returns the referenced object""" @@ -208,9 +216,31 @@ class JsonPointer(object): return doc[part] + def get_part(self, doc, part): + """ Returns the next step in the correct type """ + + if isinstance(doc, dict): + return part + + elif isinstance(doc, list): + + if part == '-': + return part + + try: + return int(part) + except ValueError: + raise JsonPointerException("'%s' is not a valid list index" % (part, )) + + else: + raise JsonPointerException("Unknown document type '%s'" % (doc.__class__,)) + + def walk(self, doc, part): """ Walks one step in doc and returns the referenced part """ + part = self.get_part(doc, part) + if isinstance(doc, dict): try: return doc[part] @@ -224,11 +254,6 @@ class JsonPointer(object): return EndOfList(doc) try: - part = int(part) - except ValueError: - raise JsonPointerException("'%s' is not a valid list index" % (part, )) - - try: return doc[part] except IndexError: |