h2non / jsonpath-ng

Finally, a JSONPath implementation for Python that aims to be standard compliant. That's all. Enjoy!
Apache License 2.0
603 stars 87 forks source link

Apply regex to leaf nodes, or filter by type? #59

Open deliciouslytyped opened 4 years ago

deliciouslytyped commented 4 years ago

Slightly related to https://github.com/h2non/jsonpath-ng/issues/58 , $..*[?(@[*] =~ "whatever")] fails in https://github.com/h2non/jsonpath-ng/blob/de4df602945b72014b4d94dbbfc947ea997fee77/jsonpath_ng/ext/filter.py#L29 with "expected string or bytes-like object" because it tries to run the regex on a list.

Is there any way to make this work?

Is there a way to apply the regex to any leaf node?

deliciouslytyped commented 4 years ago

Things are a bit of a mess between this issue and https://github.com/h2non/jsonpath-ng/issues/58 ; the nice thing to do would be to make a pr for my patches but this diff will have to do for the moment.

diff -r hiv2xlsx/venv3/Lib/site-packages/jsonpath_ng/ext/filter.py jsonpath-ng/jsonpath_ng/ext/filter.py
20,24d19
< def matcher(a,b):
<     if isinstance(a, str):
<         return True if re.search(b, a) else False
<     else:
<         return False
34c29
<     '=~': matcher,
---
>     '=~': lambda a, b: True if re.search(b, a) else False,
Only in hiv2xlsx/venv3/Lib/site-packages/jsonpath_ng/ext: __pycache__
diff -r hiv2xlsx/venv3/Lib/site-packages/jsonpath_ng/jsonpath.py jsonpath-ng/jsonpath_ng/jsonpath.py
566c566
<         if (isinstance(datum.value, list) or isinstance(datum.value, dict)) and datum.value and len(datum.value) > self.index:
---
>         if datum.value and len(datum.value) > self.index:

With these patches, the missing piece was that I should be using @.

import jsonpath_ng.ext as p
(r := [x.value for x in p.parse('$..@[?(@ =~ ".*dsa.*")]').find({1:[{2:"asd",3:"dsa"}]})])
['dsa']