[Python-ideas] JSON encoding protocol with __json__ dunder method
kissgyorgy at me.com
Thu Feb 1 15:45:13 EST 2018
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
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
or __json_encode__ and __json_decode__ or something like these.
Was there already a PEP/discussion about this?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas