I have a JSON that I am trying to do some filtering and then count the number of elements returned. However it seems to work incorrectly.
Here is the sample data and code to replicate.
import json
from jsonpath_ng.ext import *
data_json = """
{
"some_key":"some_value",
"level_1":[
{
"level_2_name" : "abc",
"level_2_attr" : "123"
},
{
"level_2_name" : "def",
"level_2_attr" : "123"
},
{
"level_2_name" : "ghi",
"level_2_attr" : "123"
}
]
}
"""
data_dict = json.loads(data_json)
print(data_dict)
path_expr = "$.level_1[? level_2_name == 'abc']['level_2_name'].`len` "
val_lst = parse(path_expr).find(data_dict)
for item in val_lst:
print(item.value)
This code block returns the value 3 which is the length of string "abc" instead of 1 which is the number of times we find "abc" in the filter.
Deep diving shows if i remove the "len" at the end , it is returning a list and the list has only one element. so the filtering is working right. Is there a bug in the library or do I need to tweak the expression?
Further analysis seems to show that "len" only works on items that are (list of list) and not on (list of items). In this case the filters are returning 'list of string' instead of 'list of list of string'.
EDIT 1 : For new repliers, I do know that len(list) can be used as python code but that is not what I am looking for. I was trying to see if there is an out of box solution and if had an error in my expression. apologies if it was not clear earlier.
EDIT 2: I gave up this approach. I had to parse a 6k line complex nested json and extract 400+ values from it in real time for my application. If I use this library it was taking ~20 secs. Doing it in python with a lot of if-else in between was able to do it in < 1 sec . So for the sake of speed abandoning this path.