This thread discusses a __json__ encoder protocol:

"adding support for a "raw output" in JSON serializer"

You actually don't have to subclass JSONEncoder; you can specify a default= method that uses isinstance(), hasattr(), or singledispatch.
- "Specializing JSON object encoding:"
  > If for_json is true (not the default), objects with a for_json() method will use the return value of that method for encoding as JSON instead of the object.

"use __json__ attribute to encode custom objects"

Simplejson supports object.for_json(), but only checks objects if for_json=True is specified.

FWIW, Jupyter notebook supports object._repr_json_() and e.g. object._repr_pretty_()

Dunder methods are name-mangled, and, by convention reserved for internal Python use: if CPython decides that object.__json__() should return a bool for whether a string is already JSON-encoded, and that breaks your excessively-presumptive dunder json method implementation, tough luck.

Singledispatch (or, indeed, creating your own utils.json.dump that's a functools.partial that just specifies a default default=) is probably fastest.

JSON5 allows things like ±inf and nan.

On Mon, Apr 6, 2020, 9:32 AM Dan Cojocaru <> wrote:

I'm not really sure how suggesting improvements to Python goes and I've found this mailing list, so I thought I'd email it.

My suggestion is related to the json built in package, and more exactly about serialising custom classes.

As of now, the process involves using a JSONEncoder class which, by default, supports the following types/values: dict, list, tuple, str, int, float, True, False, None and int- & float-derived Enums.

In order to dump a custom class to JSON, the process involves creating a new class inheriting JSONEncoder and defining the default function in order to handle custom classes.

I say that this approach is very complex and perhaps unpythonic, definitely very weird compared to other approaches.

An alternative that comes to mind and would feel more natural is adding support for recognising a __json__ function. If a class would contain such a function, the default JSONEncoder should take that function's return value instead for encoding, assuming that such returned value will be able to be then serialised.

If such a functionality would be added, many custom functions will most likely return a dict from their __json__ function, skipping the need for creating a class inheriting JSONEncoder altogether.

I hope this idea is a good one and could perhaps even get implemented in the next version of Python. 

Dan Cojocaru.
Python-ideas mailing list --
To unsubscribe send an email to
Message archived at
Code of Conduct: