Creating a custom JSON class serializable

I have a custom class, let the call be an ObjectA () class, and it has a bunch of functions, a property, etc., and I want to serialize the object using the standard json library in python, what I need to implement is to serialize this object in JSON without writing a custom encoder?

thanks

+6
source share
1 answer

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

See "JSONEncoder Extension" 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"}' 
+6
source

All Articles