Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a path extension that exposes datum's path from the jsonpath itself #176

Merged
merged 2 commits into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions jsonpath_ng/ext/iterable.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,28 @@ def __str__(self):

def __repr__(self):
return 'Keys()'

class Path(JSONPath):
"""The JSONPath referring to the path of the current object.
Concrete syntax is 'path`'.
"""

def find(self, datum):
datum = DatumInContext.wrap(datum)
try:
value = str(datum.path)
except Exception as e:
return []
else:
return [DatumInContext(value,
context=datum,
path=Path())]

def __eq__(self, other):
return isinstance(other, Path)

def __str__(self):
return '`path`'

def __repr__(self):
return 'Path()'
2 changes: 2 additions & 0 deletions jsonpath_ng/ext/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ def p_jsonpath_named_operator(self, p):
p[0] = _iterable.Len()
elif p[1] == 'keys':
p[0] = _iterable.Keys()
elif p[1] == 'path':
p[0] = _iterable.Path()
elif p[1] == 'sorted':
p[0] = _iterable.SortedThis()
elif p[1].startswith("split("):
Expand Down
6 changes: 6 additions & 0 deletions tests/test_jsonpath_rw_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@
["cow", "cat"],
id="keys_dict",
),
pytest.param(
"objects.cow.`path`",
{"objects": {"cow": "moo", "cat": "neigh"}},
"cow",
id="path_dict",
),
pytest.param(
"objects[?cow]",
{"objects": [{"cow": "moo"}, {"cat": "neigh"}]},
Expand Down