On Tue, 27 Aug 2019 at 10:22, Richard Musil email@example.com wrote:
On Tue, Aug 27, 2019 at 10:48 AM Antoine Pitrou firstname.lastname@example.org wrote:
On Sun, 11 Aug 2019 20:09:41 -0400 David Shawley email@example.com wrote:
On Aug 8, 2019, at 3:55 PM, Chris Angelico firstname.lastname@example.org wrote:
I proposed something similar about a year ago . I really like the idea of a protocol for this. Especially since the other encoders already use this approach. Should I reboot this approach? The implementation was really simple .
I think this would be worthwhile.
Here is a use case where it may remove some pain from users'life: https://bugs.python.org/issue24313
Since __json__ protocol is being raised again, I would just like to point out that during the previous discussion the term has been used in two different contexts:
- allowing complete custom serialization (i.e. controlling the JSON encoding)
Which was an approach I mostly liked, but thought it was generally not acceptable here (because of the total control of the encoding). My reasoning was that I believed that the only JSON type "lacking the full support" was really *JSON number*, so in order to keep my proposal's impact small I went on with the custom serialization just for the JSON number. That said I would consider __json__ protocol to be otherwise more elegant solution.
- only allowing serialization of Python native types (but with custom values as 'for_json' in simplejson does)
This was commented on as already achievable with custom encoder class (or custom 'default' function). I did not really care, because it did not seem to bring any advantage or a fix for my problem problem.
To resolve the bpo issue with numpy, one would need to implement complete custom serialization (1) or simply convert numpy number types into Python number types.
The key point here, IMO, is that this is precisely the sort of use case for numbers other than Decimal that people (including me) kept asking for in the original discussion.
Thanks, Antoine for finding it and flagging it here. I agree that this seems like a good reason for having *some* means of letting types decide how they should be serialised in JSON. There are still questions that need to be addressed (such as how we deal with types that don't return a well-formed JSON value) but at least we have a use case to drive the discussion now.
For example, the numpy case might be covered completely by the JSON module just adding supporting for types that provide an __index__ method. So rather than needing a new protocol, an existing one might be perfectly adequate. (Although I've not looked into this in any great detail, so it's entirely likely I've missed something critical - my point is mainly that with a proper use case, we can discuss solutions in the context of a real requirement).