I have some SQLAlchemy objects which contain lists of more SQLAlchemy objects, and so on (for about 5 levels). I wish to convert all the objects to dictionaries.
I can convert an object to a dictionary by using the __dict__
property, no problem. However, I'm having trouble figuring out the best way to convert all the nested objects as well, without having to do each level explicitly.
So far, this is the best I can come up with, but it doesn't recurse properly. It basically breaks after one pass, so there's clearly something wrong with my logic. Can you see what's wrong with it??
I am hoping to do:
all_dict = myDict(obj.__dict__)
def myDict(d):
for k,v in d.items():
if isinstance(v,list):
d[k] = [myDict(i.__dict__) for i in v]
else:
d[k] = v
return d