Recursively convert python object graph to dictionary

前端 未结 9 1614
既然无缘
既然无缘 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 11:05

    One line of code to convert an object to JSON recursively.

    import json
    
    def get_json(obj):
      return json.loads(
        json.dumps(obj, default=lambda o: getattr(o, '__dict__', str(o)))
      )
    
    obj = SomeClass()
    print("Json = ", get_json(obj))
    

提交回复
热议问题