Most of the classes (even if very simple like datetime.datetime) cannot be serialized to JSON by default.
Would it be a good idea for the default json.JSONEncoder to call the __json__ dunder method automatically if the object has one?
I can't find anything about why this protocol or PEP doesn't exists yet.
Currently almost everyone implements it like this, there are thousands of results on GitHub to this:
but there is no canonical way (Python/standard way) to do this.
It would be very nice, because a custom JSONEncoder would not be needed and
everyone could implement JSON serialization in One True Way (yay for code reuse!)
The implementation could be very simple, would look something like this:
def default(self, obj):
if hasattr(obj, '__json__'):
Or to make it easier even for decoding, it could be __to_json__ and __from_json__
or __json_encode__ and __json_decode__ or something like these.
Was there already a PEP/discussion about this?