summaryrefslogtreecommitdiff
path: root/jsonpointer.py
diff options
context:
space:
mode:
authorStefan Kögl <stefan@skoegl.net>2011-08-01 14:36:20 +0000
committerStefan Kögl <stefan@skoegl.net>2011-08-01 14:36:20 +0000
commit759aa5ea0317711e5e944a0793f783f3cc293a6a (patch)
treebfdcf55b24260d72e0a5f7f7daad24944f722e7f /jsonpointer.py
parentee717c3fee8dd11e6659a969054de6eb43f8f576 (diff)
downloadpython-json-pointer-759aa5ea0317711e5e944a0793f783f3cc293a6a.tar.gz
refactor into JsonPointer class
Diffstat (limited to 'jsonpointer.py')
-rw-r--r--jsonpointer.py61
1 files changed, 37 insertions, 24 deletions
diff --git a/jsonpointer.py b/jsonpointer.py
index 64b8137..101388e 100644
--- a/jsonpointer.py
+++ b/jsonpointer.py
@@ -69,39 +69,52 @@ def resolve_pointer(doc, pointer):
True
"""
- parts = pointer.split('/')
- if parts.pop(0) != '':
- raise JsonPointerException('location must starts with /')
+ pointer = JsonPointer(pointer)
+ return pointer.resolve(doc)
- parts = map(urllib.unquote, parts)
- for part in parts:
- doc = walk(doc, part)
+class JsonPointer(object):
+ """ A JSON Pointer that can reference parts of an JSON document """
- return doc
+ def __init__(self, pointer):
+ parts = pointer.split('/')
+ if parts.pop(0) != '':
+ raise JsonPointerException('location must starts with /')
+ self.parts = map(urllib.unquote, parts)
-def walk(doc, part):
- """ Walks one step in doc and returns the referenced part """
- if not part:
+ def resolve(self, doc):
+ """Resolves the pointer against doc and returns the referenced object"""
+
+ for part in self.parts:
+ doc = self.walk(doc, part)
+
return doc
- # Its not clear if a location "1" should be considered as 1 or "1"
- # We prefer the integer-variant if possible
- part_variants = _try_parse(part) + [part]
- for variant in part_variants:
- try:
- return doc[variant]
- except:
- continue
+ def walk(self, doc, part):
+ """ Walks one step in doc and returns the referenced part """
+
+ if not part:
+ return doc
- raise JsonPointerException("'%s' not found in %s" % (part, doc))
+ # Its not clear if a location "1" should be considered as 1 or "1"
+ # We prefer the integer-variant if possible
+ part_variants = self._try_parse(part) + [part]
+ for variant in part_variants:
+ try:
+ return doc[variant]
+ except:
+ continue
-def _try_parse(val, cls=int):
- try:
- return [cls(val)]
- except:
- return []
+ raise JsonPointerException("'%s' not found in %s" % (part, doc))
+
+
+ @staticmethod
+ def _try_parse(val, cls=int):
+ try:
+ return [cls(val)]
+ except:
+ return []