Make a Custom Class JSON serializable

人盡茶涼 提交于 2021-01-02 05:52:41

问题


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?

Thank you


回答1:


Subclass json.JSONEncoder, and then construct a suitable dictionary or array.

See "Extending JSONEncoder" behind this link

Like this:

>>> 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"}'


来源:https://stackoverflow.com/questions/23088565/make-a-custom-class-json-serializable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!