Skip to content

Commit

Permalink
Keys removal (filter) with path filtering
Browse files Browse the repository at this point in the history
  • Loading branch information
cmin764 authored and michaelmior committed Sep 13, 2023
1 parent 36c1bad commit 32e9a09
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
10 changes: 10 additions & 0 deletions jsonpath_ng/ext/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,16 @@ def find(self, datum):
len(list(filter(lambda x: x.find(datum.value[i]),
self.expressions))))]

def filter(self, fn, data):
# NOTE: We reverse the order just to make sure the indexes are preserved upon
# removal.
for datum in reversed(self.find(data)):
index_obj = datum.path
if isinstance(data, dict):
index_obj.index = list(data)[index_obj.index]
index_obj.filter(fn, data)
return data

def update(self, data, val):
if type(data) is list:
for index, item in enumerate(data):
Expand Down
8 changes: 8 additions & 0 deletions tests/test_jsonpath_rw_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,14 @@ def check_paths(self, test_cases):
else:
assert str(result.path) == target

def test_filter_with_filtering(self):
data = {"foos": [{"id": 1, "name": "first"}, {"id": 2, "name": "second"}]}
result = parser.parse('$.foos[?(@.name=="second")]').filter(
lambda _: True, data
)
names = [item["name"] for item in result["foos"]]
assert "second" not in names

def test_fields_paths(self):
jsonpath.auto_id_field = None
self.check_paths([('foo', {'foo': 'baz'}, ['foo']),
Expand Down

0 comments on commit 32e9a09

Please sign in to comment.