[Python-ideas] Serialization of custom classes.

Masklinn masklinn at masklinn.net
Wed Mar 30 13:05:49 CEST 2011

On 2011-03-30, at 12:42 , Jakob Bowyer wrote:
> My suggested fix and an idea used by several others could be to add a __json__
> method to objects, this method would be tried by json.dumps() before it tries to
> serialise the argument. It should return all of the instance variables in a json
> format and any other infomation considered to be correct for the dump.
> This could be extended to provide a __json__ and a __jsons__ format where the
> latter returns a string format of the __json__ serialzation an example of which
> (crudely constructed ofc) is below. But for now I consider __json__ to return a
> string serialized for json dumping.

The documented method for serializing non-literal types (such as custom types) is to simply provide subclasses of ``JSONEncoder`` overriding  the method ``default``. Why not just do that?

Hell, you could even implement your serialization scheme through this, no need for "customjsondumps".

More information about the Python-ideas mailing list