I have a recursive function that examines a json object. It captures the data when I try to loop the data, it works for one but not the other. I need help determining what type of data the returned data is show I can loop the data.
targetType = 'equal'
def find_data(lookup_key, jsonData, search_result = []):
if type(jsonData) == dict:
for key, value in jsonData.items():
if targetType == 'equal' and key == lookup_key:
search_result.append(value)
elif targetType == 'regex' and pattern.search(key):
search_result.append(value)
find_data(lookup_key, value, search_result)
elif type(jsonData) == list:
for element in jsonData:
find_data(lookup_key, element, search_result)
return search_result
json_obj = {
"data": [
{"stats":[{"num":1,"Count":[0,1,2]},{"num":2,"Count":[3,4,5]}, {"num":3,"Count":[6,7,8]},
{"num":4,"Count":[9,10,11]}, {"num":5,"Count":[12,13,14]},
{"num":6,"Count":[15,16,17]},{"num":7,"Count":[18,19,20]}]},
{"settings":[{"num":8,"Channel1":[[21,22,23],[1,2,3],[4,5,6]]}]}]}
target_key = "Count"
#target_key = "Channel1"
data = find_data(target_key,json_obj, [])
for item in data:
print(item)
When ran with target_key = "Count"
a item (list) prints one per loop. When I use target_key = "Channel1"
the loop fails I have to to use for item in data[0]
. How can I determine which loop to use. I tried if all(isinstance(i, list) for i in data):
to determine it is was a nested loop, but both return true.
Here is the return from Count [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14], [15, 16, 17], [18, 19, 20]]
here is the return from Channel1 [[[21, 22, 23], [1, 2, 3], [4, 5, 6]]]