Skip to content

Commit b691dae

Browse files
davidmichaelmior
authored andcommitted
Added path extension that exposes datum's path from the jsonpath expression itself.
1 parent 8a62341 commit b691dae

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

jsonpath_ng/ext/iterable.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,29 @@ def __str__(self):
116116

117117
def __repr__(self):
118118
return 'Keys()'
119+
120+
class Path(JSONPath):
121+
"""The JSONPath referring to the path of the current object.
122+
Concrete syntax is 'path`'.
123+
"""
124+
125+
def find(self, datum):
126+
datum = DatumInContext.wrap(datum)
127+
try:
128+
value = str(datum.path)
129+
except Exception as e:
130+
return []
131+
else:
132+
return [DatumInContext(value,
133+
return [DatumInContext(value,
134+
context=datum,
135+
path=Path())]
136+
137+
def __eq__(self, other):
138+
return isinstance(other, Path)
139+
140+
def __str__(self):
141+
return '`path`'
142+
143+
def __repr__(self):
144+
return 'Path()'

jsonpath_ng/ext/parser.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ def p_jsonpath_named_operator(self, p):
9696
p[0] = _iterable.Len()
9797
elif p[1] == 'keys':
9898
p[0] = _iterable.Keys()
99+
elif p[1] == 'path':
100+
p[0] = _iterable.Path()
99101
elif p[1] == 'sorted':
100102
p[0] = _iterable.SortedThis()
101103
elif p[1].startswith("split("):

tests/test_jsonpath_rw_ext.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,12 @@
6868
["cow", "cat"],
6969
id="keys_dict",
7070
),
71+
pytest.param(
72+
"objects.cow.`path`",
73+
{"objects": {"cow": "moo", "cat": "neigh"}},
74+
"cow",
75+
id="path_dict",
76+
),
7177
pytest.param(
7278
"objects[?cow]",
7379
{"objects": [{"cow": "moo"}, {"cat": "neigh"}]},

0 commit comments

Comments
 (0)