I have this recursive method that is used to dig into a deeply nested object and find an attribute and return that attribute. The method works well enough to dig into the object and find the nested attribute however, I am having trouble defining the base case to actually return it once it's found.
def find_nested(d):
if isinstance(d, dict) and 'target' in d:
print(type(d['target']))
return d['target']
if isinstance(d, dict):
for k, v in d.items():
find_nested(v)
elif hasattr(d, '__iter__') and not isinstance(d, str):
for item in d:
find_nested(item)
Here the return d['target'] always returns None. I've tried setting up the base case a couple of different ways but I can't seem to figure out to bubble the found attribute to the top. If 'target' doesn't exist the recursive method should just return an empty array but when I tried to set that up. It would always just return the empty array.
Any ideas?
I've tried adding return statements to the recursive calls but something weird happens. It never makes it to the base case. That print statement in the first conditional is never executed
def find_nested(d):
if isinstance(d, dict) and 'target' in d:
print(type(d['target']))
return d['target']
if isinstance(d, dict):
for k, v in d.items():
return find_nested(v)
elif hasattr(d, '__iter__') and not isinstance(d, str):
for item in d:
return find_nested(item)
Here's a simple example of the nested object
{"sort":{"method":"BEST_MATCH"},"pagination":{"limit":20,"offset":0},"Do":[{"types":{"do":[{"tests":{"must":["testItem"]},"target1":{"target":["WHAT_I_AM_CAPTURING"]}}]}}],"stats":{"count_all_records":true}}
EDIT: Based on the comments it seems that the issue w/ the return statements is that there are objects w/ in the provided object that can be arrays of objects. The goal here is to dig through every object in the main object to return the 'target' object however, my recursive method is not handling the array of objects correctly.