JSON encoding protocol with __json__ dunder method

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

On Thu, Feb 01, 2018 at 08:45:13PM +0000, Kiss, György wrote:
See: http://bugs.python.org/issue27362 This has been discussed before: https://mail.python.org/pipermail/python-ideas/2010-July/007811.html https://mail.python.org/pipermail/python-ideas/2011-March/009644.html Please familiarise yourself with the objections and counter-arguments already discussed before trying to debate this again. -- Steve

On Thu, Feb 01, 2018 at 08:45:13PM +0000, Kiss, György wrote:
See: http://bugs.python.org/issue27362 This has been discussed before: https://mail.python.org/pipermail/python-ideas/2010-July/007811.html https://mail.python.org/pipermail/python-ideas/2011-March/009644.html Please familiarise yourself with the objections and counter-arguments already discussed before trying to debate this again. -- Steve
participants (2)
-
Kiss, György
-
Steven D'Aprano