code base 5000
code base 5000

Reputation: 4112

Make a Custom Class JSON serializable

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

Answers (1)

FrobberOfBits
FrobberOfBits

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

Related Questions