问题
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