Possible Duplicate:
Python serializable objects json
我需要知道如何将动态 python 对象转换为 JSON。对象必须能够有多个级别对象的子对象。例如:
class C(): pass
class D(): pass
c = C()
c.dynProperty1 = "something"
c.dynProperty2 = { 1, 3, 5, 7, 9 }
c.d = D()
c.d.dynProperty3 = "d.something"
# ... convert c to json ...
使用python 2.6以下代码:
import json
class C(): pass
class D(): pass
c = C()
c.what = "now?"
c.now = "what?"
c.d = D()
c.d.what = "d.what"
json.dumps(c.__dict__)
产生以下错误:
TypeError: <__main__.D instance at 0x99237ec> is not JSON serializable
我不知道用户可能会将哪些类型的子对象放入 c
。是否有足够智能的解决方案来检测属性是否为对象并自动解析它的 __dict__
?
更新以包含 c
上的子对象。
最佳答案
指定default=
参数(doc):
json.dumps(c, default=lambda o: o.__dict__)
关于python - 将动态python对象转换为json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408647/