I am trying to parse the output of an API calls which is a json object with nested dict and lists, with depth not known. I saw several example of recursive functions getting a key value from nested list/dict but I want to get the specific order as well for the correctness of the structure. so for example:
response = {'a': {'b': {'b1': 1, 'b2': 2},
'c': [{'c1': 3,'c2': [{'x':55,'y':56},{'x':65,'y':66}]},
{'c1': 5,'c2': [{'x':75,'y':76},{'x':85,'y':86}]}]
}
}
fun(response,"a-c-c2-x") should return [55,65,75,85]
fun(response,"a-b-b2") should return [2]
fun(response,"a-b2-b") should return []
what I have so far that is not working :)
def get_response_values(response=None, key=None, result=None):
print("1-r: {} - key: {} -r:{}".format(response, key, result))
if result is None:
result = []
if '-' in key:
if isinstance(response, dict):
index = key.find('-')
response = response[key[:index]]
key = key[index+1:]
print("3-r: {} - key: {} -r:{}".format(response, key, result))
get_response_values(response, key, result)
if isinstance(response, list):
index = key.find('-')
key = key[index+1:]
for item in response:
print("4-r: {} - key: {} -r:{}".format(item, key, result))
get_response_values(item, key, result)
else:
try:
result.append(response[key])
print("2-r: {} - key: {} -r:{}".format(response, key, result))
return result
except:
print("5-r: {} - key: {} -r:{}".format(response, key, result))
return result
return result