【发布时间】: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)
【问题讨论】:
-
这能回答你的问题吗? How to make a class JSON serializable
标签: python json serialization