Jacob
Jacob

Reputation: 810

Convert object attributes to dict

class foo:
    def __init__(self,name):
        self.name = name
        #other attributes
        self.children = [] #Child objects in self.children

    def convert(self):
        return vars(self)

When using vars(foo) or foo.__dict__ the objects in self.children aren't converted into dictionaries too, returning a dictionary like this:

{'name': 'name', 'children': [object1,object2...]}

These 'child' objects are also instances of the foo class. At first I tried using dict['children'] = [vars(item) for item in dict['children']] to convert these objects but unfortunately this doesn't work for children of children. Is there a recursive function I can create to convert all these objects and their children?

Upvotes: 0

Views: 5205

Answers (1)

Barmar
Barmar

Reputation: 781078

Do it with a recursive function. Get the vars for the object, then replace the children list with a list of converted children.

def convert(self):
    d = dict(vars(self)) # Copy the vars() dictionary
    d['children'] = [c.convert() for c in self.children]
    return d

Upvotes: 1

Related Questions