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