gpt4 book ai didi

python - 自定义对象列表json在python中序列化

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:33 28 4
gpt4 key购买 nike

对于自定义对象,我可以使用 JSONEncoder 将其编码为 json。

class CustomEncoder(JSONEncoder):
def encode(self, custom):
prop_dict = {}
for prop in Custom.all_properties_names():
if custom.__getattribute__(prop) is not None:
if prop is 'created_timestamp':
prop_dict.update({prop: custom.__getattribute__(
prop).isoformat()})
else:
prop_dict.update({prop: custom.__getattribute__(prop)})
return prop_dict

为了生成 json,我正在使用 json.dumps(custom, cls=CustomEncoder, indent=True)

现在我有一个自定义类对象的列表。如何将列表转成json?

custom_list = //get custom object list from service

如何将整个列表转换为 json?我是否需要迭代和捕获每个自定义对象的 json 并附加到以逗号分隔的列表?我觉得这里应该缺少一些直截了当的东西。

最佳答案

自定义编码器仅在需要时调用。如果您有 JSON 库认为它可以编码的自定义内容,例如字符串或字典,则不会调用自定义编码器。以下示例显示了对一个对象或包含一个对象的列表进行编码,使用单个自定义编码器:

import json

class Custom(object):
pass

class CustomEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Custom):
return 'TASTY'
return CustomEncoder(self, o)

print json.dumps( Custom(), cls=CustomEncoder )
print json.dumps( [1, [2,'three'], Custom()], cls=CustomEncoder )

输出:

"TASTY"
[1, [2, "three"], "TASTY"]

关于python - 自定义对象列表json在python中序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23966944/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com