sileht / python-jsonpath-rw-ext

Extensions for JSONPath RW
Apache License 2.0
59 stars 19 forks source link

KeyError when applying filter #2

Closed VictorShima closed 8 years ago

VictorShima commented 8 years ago

Hello,

I just found out about your package and tried to test this code:

import jsonpath_rw_ext
jsonpath_rw_ext.parse('foo[*][?(@.baz==1)]').find( {'foo': [{'baz': 1}, {'baz': 2}]} )

But I receive a KeyError. Could you check this out?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/site-packages/jsonpath_rw/jsonpath.py", line 228, in find
    for submatch in self.right.find(subdata)]
  File "/usr/lib/python2.7/site-packages/jsonpath_rw_ext/_filter.py", line 47, in find
    self.expressions))))]
  File "/usr/lib/python2.7/site-packages/jsonpath_rw_ext/_filter.py", line 46, in <lambda>
    len(list(filter(lambda x: x.find(datum.value[i]),
KeyError: 0

PS: thank you a lot for having the initiative to develop these jsonpath extensions =)

sileht commented 8 years ago

You should use 'foo[?(@.baz==1)]' to find [{'baz': 1}] from {'foo': [{'baz': 1}, {'baz': 2}]}

Or the data must be {'foo': [[{'baz': 1}, {'baz': 2}]]} (notes the double list) to 'foo[*][?(@.baz==1)]' to find [{'baz': 1}]

Anyways the code shouldn't raise an exception but just return an empty list. I have fixed that here:

https://github.com/sileht/python-jsonpath-rw-ext/commit/da3e74d4ffd5ca11faad6b0a3c76356a51e2cf28