Permalink
Browse files

add JsonPointer.to_last() for use in jsonpatch

  • Loading branch information...
1 parent 164a915 commit 1e818af78ec962d6b351f3de89d771dfa86a7368 @stefankoegl committed Nov 15, 2012
Showing with 30 additions and 5 deletions.
  1. +30 −5 jsonpointer.py
View
35 jsonpointer.py
@@ -146,6 +146,14 @@ def __init__(self, pointer):
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 @@ def _set_value(doc, part, value):
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 @@ def walk(self, doc, part):
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:

0 comments on commit 1e818af

Please sign in to comment.