【发布时间】:2020-12-05 04:16:37
【问题描述】:
我正在尝试使用具有继承性的 python 类重新创建以下 JSON:
{"attribute1": "c1"
"attribute2": {"attribute3" : "test"}
}
到目前为止,我有这个代码:
class class1():
def __init__(self, attribute1):
self.attribute1 = attribute1
class class2(class1):
def __init__(self, attribute2):
class1.__init__(self, 'test')
self.attribute2 = attribute2
c1 = class1('c1')
c2 = class2(c1)
print(json.dumps(c1.__dict__))
渲染:
{"attribute1": "c1"}
如果我尝试将变量 c2 转换为 JSON:
print(json.dumps(c2.__dict__))
我收到错误:
TypeError: Object of type class1 is not JSON serializable
class1 不应该是可序列化的,因为我之前使用 print(json.dumps(c1.__dict__)) 对其进行了转换
【问题讨论】:
-
class1 dict 是可序列化的,但 class1 本身不是。您可以将函数传递给转储以覆盖它。例如
json.dumps(c2, default=lambda c: c.__dict__)
标签: python json oop inheritance data-modeling