Recursively convert python object graph to dictionary

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

    Looked at all solutions, and @hbristow's answer was closest to what I was looking for. Added enum.Enum handling since this was causing a RecursionError: maximum recursion depth exceeded error and reordered objects with __slots__ to have precedence of objects defining __dict__.

    def todict(obj):
      """
      Recursively convert a Python object graph to sequences (lists)
      and mappings (dicts) of primitives (bool, int, float, string, ...)
      """
      if isinstance(obj, str):
        return obj
      elif isinstance(obj, enum.Enum):
        return str(obj)
      elif isinstance(obj, dict):
        return dict((key, todict(val)) for key, val in obj.items())
      elif isinstance(obj, collections.Iterable):
        return [todict(val) for val in obj]
      elif hasattr(obj, '__slots__'):
        return todict(dict((name, getattr(obj, name)) for name in getattr(obj, '__slots__')))
      elif hasattr(obj, '__dict__'):
        return todict(vars(obj))
      return obj
    

提交回复
热议问题