Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 支持嵌套类型中自定义类的默认序列化_Python_Json_Jsonserializer - Fatal编程技术网

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}]