Recursively convert python object graph to dictionary

前端 未结 9 1625
既然无缘
既然无缘 2020-12-04 10:25

I\'m trying to convert the data from a simple object graph into a dictionary. I don\'t need type information or methods and I don\'t need to be able to convert it back to an

9条回答
  •  广开言路
    2020-12-04 10:54

    def list_object_to_dict(lst):
        return_list = []
        for l in lst:
            return_list.append(object_to_dict(l))
        return return_list
    
    def object_to_dict(object):
        dict = vars(object)
        for k,v in dict.items():
            if type(v).__name__ not in ['list', 'dict', 'str', 'int', 'float']:
                    dict[k] = object_to_dict(v)
            if type(v) is list:
                dict[k] = list_object_to_dict(v)
        return dict
    

提交回复
热议问题