From dba7c666e8828bab08d1687e9264bcc9e803ee25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Sat, 22 Mar 2014 18:48:30 +0100 Subject: add JsonPointer.path and JsonPointer.from_parts --- jsonpointer.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/jsonpointer.py b/jsonpointer.py index ddb5d8c..81fad76 100644 --- a/jsonpointer.py +++ b/jsonpointer.py @@ -247,6 +247,17 @@ class JsonPointer(object): return len(self.parts) > len(ptr.parts) and \ self.parts[:len(ptr.parts)] == ptr.parts + @property + def path(self): + """ Returns the string representation of the pointer + + >>> ptr = JsonPointer('/~0/0/~1') + >>> ptr.path + u'/~0/0/~1' + """ + parts = [part.replace('~', '~0') for part in self.parts] + parts = [part.replace('/', '~1') for part in parts] + return '/' + '/'.join(parts) def __eq__(self, other): """ compares a pointer to another object @@ -264,6 +275,20 @@ class JsonPointer(object): def __hash__(self): return hash(tuple(self.parts)) + @classmethod + def from_parts(cls, parts): + """ Constructs a JsonPointer from a list of (unescaped) paths + + >>> JsonPointer.from_parts(['a', '~', '/', 0]).path + u'/a/~0/~1/0' + """ + parts = [str(part) for part in parts] + parts = [part.replace('~', '~0') for part in parts] + parts = [part.replace('/', '~1') for part in parts] + ptr = cls('/' + '/'.join(parts)) + return ptr + + def pairwise(iterable): """ s -> (s0,s1), (s1,s2), (s2, s3), ... -- cgit v1.2.1