Skip to content

Commit 32e9a09

Browse files
cmin764michaelmior
authored andcommitted
Keys removal (filter) with path filtering
1 parent 36c1bad commit 32e9a09

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

jsonpath_ng/ext/filter.py

+10
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,16 @@ def find(self, datum):
5353
len(list(filter(lambda x: x.find(datum.value[i]),
5454
self.expressions))))]
5555

56+
def filter(self, fn, data):
57+
# NOTE: We reverse the order just to make sure the indexes are preserved upon
58+
# removal.
59+
for datum in reversed(self.find(data)):
60+
index_obj = datum.path
61+
if isinstance(data, dict):
62+
index_obj.index = list(data)[index_obj.index]
63+
index_obj.filter(fn, data)
64+
return data
65+
5666
def update(self, data, val):
5767
if type(data) is list:
5868
for index, item in enumerate(data):

tests/test_jsonpath_rw_ext.py

+8
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,14 @@ def check_paths(self, test_cases):
479479
else:
480480
assert str(result.path) == target
481481

482+
def test_filter_with_filtering(self):
483+
data = {"foos": [{"id": 1, "name": "first"}, {"id": 2, "name": "second"}]}
484+
result = parser.parse('$.foos[?(@.name=="second")]').filter(
485+
lambda _: True, data
486+
)
487+
names = [item["name"] for item in result["foos"]]
488+
assert "second" not in names
489+
482490
def test_fields_paths(self):
483491
jsonpath.auto_id_field = None
484492
self.check_paths([('foo', {'foo': 'baz'}, ['foo']),

0 commit comments

Comments
 (0)