Skip to content

Commit dba7c66

Browse files
committed
add JsonPointer.path and JsonPointer.from_parts
1 parent 28ee1bb commit dba7c66

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

jsonpointer.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,17 @@ def contains(self, ptr):
247247
return len(self.parts) > len(ptr.parts) and \
248248
self.parts[:len(ptr.parts)] == ptr.parts
249249

250+
@property
251+
def path(self):
252+
""" Returns the string representation of the pointer
253+
254+
>>> ptr = JsonPointer('/~0/0/~1')
255+
>>> ptr.path
256+
u'/~0/0/~1'
257+
"""
258+
parts = [part.replace('~', '~0') for part in self.parts]
259+
parts = [part.replace('/', '~1') for part in parts]
260+
return '/' + '/'.join(parts)
250261

251262
def __eq__(self, other):
252263
""" compares a pointer to another object
@@ -264,6 +275,20 @@ def __eq__(self, other):
264275
def __hash__(self):
265276
return hash(tuple(self.parts))
266277

278+
@classmethod
279+
def from_parts(cls, parts):
280+
""" Constructs a JsonPointer from a list of (unescaped) paths
281+
282+
>>> JsonPointer.from_parts(['a', '~', '/', 0]).path
283+
u'/a/~0/~1/0'
284+
"""
285+
parts = [str(part) for part in parts]
286+
parts = [part.replace('~', '~0') for part in parts]
287+
parts = [part.replace('/', '~1') for part in parts]
288+
ptr = cls('/' + '/'.join(parts))
289+
return ptr
290+
291+
267292

268293
def pairwise(iterable):
269294
""" s -> (s0,s1), (s1,s2), (s2, s3), ...

0 commit comments

Comments
 (0)