【问题标题】:JSON serializing a class with attribute is an instance of another classJSON序列化具有属性的类是另一个类的实例
【发布时间】:2022-06-14 22:55:25
【问题描述】:

假设我有这个代码:

import json

class Foo:
    def __init__(self):
        self.x=1
        self.y=2
    
f=Foo()

x=json.dumps(vars(f))

print(x)

结果:{"x": 1, "y": 2}

此代码有效,因为 f 的所有属性都是 Python 内置类型 (int)

但是当我添加另一个类时:

class Bar:
    def __init__(self):
        self.bar=3

Foo 类有一个Bar 的实例:

class Foo:
    def __init__(self):
        self.x=1
        self.y=2
        self.bar=Bar()

序列化不起作用,引发异常TypeError: Object of type Bar is not JSON serializable 因为Bar 是自定义类型

如何让它发挥作用?

完整代码:

import json

class Bar:
    def __init__(self):
        self.bar=3

class Foo:
    def __init__(self):
        self.x=1
        self.y=2
        self.bar=Bar()
    
f=Foo()

x=json.dumps(vars(f))

print(x)

【问题讨论】:

标签: python json serialization


猜你喜欢
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多