From 90f41b923e1fc1df94d7f722594f0e3f3069e6d3 Mon Sep 17 00:00:00 2001 From: david Date: Tue, 30 Jul 2024 21:13:53 +0200 Subject: [PATCH 1/2] Added `path` extension that exposes datum's path from the jsonpath expression itself. --- jsonpath_ng/ext/iterable.py | 26 ++++++++++++++++++++++++++ jsonpath_ng/ext/parser.py | 2 ++ tests/test_jsonpath_rw_ext.py | 6 ++++++ 3 files changed, 34 insertions(+) diff --git a/jsonpath_ng/ext/iterable.py b/jsonpath_ng/ext/iterable.py index 40ae1eb..5fb6461 100644 --- a/jsonpath_ng/ext/iterable.py +++ b/jsonpath_ng/ext/iterable.py @@ -116,3 +116,29 @@ 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, + 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()' diff --git a/jsonpath_ng/ext/parser.py b/jsonpath_ng/ext/parser.py index 756b72c..fa67f4f 100644 --- a/jsonpath_ng/ext/parser.py +++ b/jsonpath_ng/ext/parser.py @@ -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("): diff --git a/tests/test_jsonpath_rw_ext.py b/tests/test_jsonpath_rw_ext.py index a4876d5..744ee7d 100644 --- a/tests/test_jsonpath_rw_ext.py +++ b/tests/test_jsonpath_rw_ext.py @@ -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"}]}, From e9a31111207225d7ccd3b90d815df567dfdaeb4e Mon Sep 17 00:00:00 2001 From: david Date: Tue, 30 Jul 2024 22:57:20 +0200 Subject: [PATCH 2/2] Typo: duplicate line removed. --- jsonpath_ng/ext/iterable.py | 1 - 1 file changed, 1 deletion(-) diff --git a/jsonpath_ng/ext/iterable.py b/jsonpath_ng/ext/iterable.py index 5fb6461..c5cd0dc 100644 --- a/jsonpath_ng/ext/iterable.py +++ b/jsonpath_ng/ext/iterable.py @@ -129,7 +129,6 @@ def find(self, datum): except Exception as e: return [] else: - return [DatumInContext(value, return [DatumInContext(value, context=datum, path=Path())]