使自定义类JSON可序列化 [英] Make a Custom Class JSON serializable
本文介绍了使自定义类JSON可序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义类,让我们称之为ObjectA()类,它具有许多函数,属性等.我想使用python中的标准json库序列化对象,我需要做什么?实现该对象将序列化为JSON,而无需编写自定义编码器?
I have a custom class, let's call is class ObjectA(), and it have a bunch of functions, property, etc.., and I want to serialize object using the standard json library in python, what do I have to implement that this object will serialize to JSON without write a custom encoder?
谢谢
推荐答案
子类json.JSONEncoder,然后构造一个合适的字典或数组.
Subclass json.JSONEncoder, and then construct a suitable dictionary or array.
赞:
>>> class A: pass
...
>>> a = A()
>>> a.foo = "bar"
>>> import json
>>>
>>> class MyEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, A):
... return { "foo" : obj.foo }
... return json.JSONEncoder.default(self, obj)
...
>>> json.dumps(a, cls=MyEncoder)
'{"foo": "bar"}'
这篇关于使自定义类JSON可序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文