Reputation: 4112
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
Upvotes: 11
Views: 18903
Reputation: 18022
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"}'
Upvotes: 13