I am trying to filter elements of my JSON data which contain specific values in an array with jsonpath_ng in Python. The data looks like
[
{
"id": "a",
"test": [
"a1",
"a2"
]
},
{
"id": "b",
"test": [
"a1",
"a3"
]
}
]
Testing the data in PyCharm with the query $[?(@.test contains "a2")]
or $[?("a2" in @.test)]
works just fine and returns the expected result
[
{
"id": "a",
"test": [
"a1",
"a2"
]
}
]
Trying this with jsonpath_ng
in Python unfortunately results in an error...
from jsonpath_ng.ext import parse
a = [{"id": "a", "test": ["a1", "a2"]}, {"id": "b", "test": ["a1", "a3"]}]
jpexpr = parse('$[?(@.test contains "a2")]')
results in an error jsonpath_ng.exceptions.JsonPathParserError: Parse error at 1:11 near token contains (ID)
. Using jpexpr = parse('$[?("a2" in @.test)]')
shows a similair behaviour jsonpath_ng.exceptions.JsonPathParserError: Parse error at 1:9 near token in (ID)
Neither with searching Google nor SO could I find an answer whether I'm doing something wrong of if there is a limitation in jsonpath_ng
.
Is there just no support of this filter in jsonpath_ng
? Does anyone have a great idea for a workaround if this was the case?
Thank you all for your assistance, .kai
jpexpr = parse('$[?(@..test[?(@ == "a2")].`len` > 0)]')
did the job for me...
from jsonpath_ng.ext import parse
a = [{"id": "a", "test": ["a1", "a2"]}, {"id": "b", "test": ["a1", "a3"]}]
jpexpr = parse('$[?(@..test[?(@ == "a2")].`len` > 0)]')
for i in jpexpr.find(a):
print(i.value)
resulted in
{'id': 'a', 'test': ['a1', 'a2']}
exactly as I wanted.