[Python-ideas] JSON encoding protocol with __json__ dunder method
Kiss, György
kissgyorgy at me.com
Thu Feb 1 15:45:13 EST 2018
Hi!
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:
https://github.com/search?l=Python&q=def+__json__&type=Code&utf8=%E2%9C%93
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:
class JSONEncoder:
def default(self, obj):
if hasattr(obj, '__json__'):
return obj.__json__()
return current_implementation
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?
György
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180201/8178182f/attachment.html>
More information about the Python-ideas
mailing list