【问题标题】:Create JSON from Python classes with inheritence从具有继承的 Python 类创建 JSON
【发布时间】: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


【解决方案1】:

class1 不应该是可序列化的,因为我之前使用 print(json.dumps(c1.dict)) 进行转换

这不是 JSON 的工作方式。它期望在每个级别找到一个字典。当你运行时,json.dumps(c2.__dict__) 你已经帮助它找到了 c2' 的字典,但你没有告诉它如何找到 c1 的字典。它不会记住你之前给json.dumps(c1.__dict__)的电话

我正在尝试使用带有继承的 python 类重新创建以下 JSON

这可能不会完全解决。嵌套 JSON 模型 HAS-A relationships 而继承模型 IS-A relationships

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多