Recursively convert python object graph to dictionary

前端 未结 9 1608
既然无缘
既然无缘 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:46

    An amalgamation of my own attempt and clues derived from Anurag Uniyal and Lennart Regebro's answers works best for me:

    def todict(obj, classkey=None):
        if isinstance(obj, dict):
            data = {}
            for (k, v) in obj.items():
                data[k] = todict(v, classkey)
            return data
        elif hasattr(obj, "_ast"):
            return todict(obj._ast())
        elif hasattr(obj, "__iter__") and not isinstance(obj, str):
            return [todict(v, classkey) for v in obj]
        elif hasattr(obj, "__dict__"):
            data = dict([(key, todict(value, classkey)) 
                for key, value in obj.__dict__.items() 
                if not callable(value) and not key.startswith('_')])
            if classkey is not None and hasattr(obj, "__class__"):
                data[classkey] = obj.__class__.__name__
            return data
        else:
            return obj
    

提交回复
热议问题