Python 支持嵌套类型中自定义类的默认序列化
我定义了一个类Python 支持嵌套类型中自定义类的默认序列化,python,json,jsonserializer,Python,Json,Jsonserializer,我定义了一个类a,并在其他类、容器和嵌套类型中使用a的对象 范例 a = A() b = [a,3,'hello' c = {'hey': b, 'huy': 3} d = [a,b,c] 我对d的json表示感兴趣,因此,我当然必须指定遇到A实例时的行为方式 对于类“A”的对象,我想得到这个(注意,我跳过了att2,这表明我不知道如何使用类似A的东西 但这不起作用,并且提出了上述链接第179行的例外情况。我的代码出了什么问题?默认的JSON编码器(您链接到的)只知道如何处理诸如dict、列表
a
,并在其他类、容器和嵌套类型中使用a
的对象
范例
a = A()
b = [a,3,'hello'
c = {'hey': b, 'huy': 3}
d = [a,b,c]
我对d
的json表示感兴趣,因此,我当然必须指定遇到A
实例时的行为方式
对于类“A”的对象,我想得到这个(注意,我跳过了att2,这表明我不知道如何使用类似A的东西
但这不起作用,并且提出了上述链接第179行的例外情况。我的代码出了什么问题?默认的JSON编码器(您链接到的)只知道如何处理诸如dict、列表、字符串和数字等“简单”的事情。它不尝试序列化类,因此没有可以在类上实现的“特殊”方法使其可JSON序列化。基本上,如果您想使用json.dumps
,您必须传递一些额外的内容,以便使其与自定义类一起工作
当编码器不知道如何处理对象时,它调用default
方法。基于您的问题,我相信您已经发现了这一点,但是您对default
方法应该放在哪里有些困惑。下面是一个例子,它可以满足您的需求:
import json
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
raise TypeError(f'Object of type {o.__class__.__name__} is not JSON serializable')
class A(object):
def __init__(self):
self.data = 'stuff'
self.other_data = 'other stuff'
def to_json(self):
return {'data': self.data}
a = A()
b = [a, 3, 'hello']
c = {'hey': b, 'huy': 3}
d = [a, b, c]
print(json.dumps(d, default=default))
打印出:
[{"data": "stuff"}, [{"data": "stuff"}, 3, "hello"], {"hey": [{"data": "stuff"}, 3, "hello"], "huy": 3}]
请注意,每个自定义类现在只需要实现to_json
方法,所有内容都将正确序列化(假设您在调用json.dumps
时将自定义default
函数传入)。这就是我想要的简单答案!谢谢
import json
def default(o):
if hasattr(o, 'to_json'):
return o.to_json()
raise TypeError(f'Object of type {o.__class__.__name__} is not JSON serializable')
class A(object):
def __init__(self):
self.data = 'stuff'
self.other_data = 'other stuff'
def to_json(self):
return {'data': self.data}
a = A()
b = [a, 3, 'hello']
c = {'hey': b, 'huy': 3}
d = [a, b, c]
print(json.dumps(d, default=default))
[{"data": "stuff"}, [{"data": "stuff"}, 3, "hello"], {"hey": [{"data": "stuff"}, 3, "hello"], "huy": 3}]