On Thu, 8 Aug 2019 at 18:53, Chris Angelico email@example.com wrote:
On Fri, Aug 9, 2019 at 6:31 AM Richard Musil firstname.lastname@example.org wrote:
Chris Angelico wrote:
- Should there be a protocol obj.__json__() to return a string
representation of an object for direct insertion into a JSON file?
However, this is a much broader topic, and if you want to push for that, I would recommend starting a new thread. As Andrew pointed out, trying to get bit-for-bit identical JSON representations out of different encoders is usually a bad idea.
I am not sure I have ever asked for bit-for-bit identical JSON
representation. I have always only mentioned `decimal.Decimal` and the lack of proper way to encode it (while having the proper way of decoding it), and if you read the subject of the OP it is asking for "raw output" (in the encoder, nothing about underlying representation) which if I understand your two options basically corresponds to the second one and is probably addressed elsewhere far more thoroughly.
If you're checking hashes, you need it to be bit-for-bit identical. But if what you REALLY want is for a Decimal to be represented in JSON as a native number, then I think that is a very reasonable feature request. The question is, how should it be done? And there are multiple viable options.
I'd recommend, rather than requesting a way to create raw output, that you request a way to either (a) recognize Decimals in the default JSON encoder, both the Python and C implementations thereof; or (b) create a protocol such as __json__ to allow any object to choose how it represents itself. You'll probably find a reasonable level of support for either of those suggestions.
I spent some minutes now trying to encode a Decimal as a JSON "Number" using Python native encoder - it really is not possible. The level of customization for Python encoders just allows a method ("default") that have to return a "known" object type - and if it returns a string, it is included with quotes in the final output - which defeats writting numbers.
So - there is clearly the need for more customization capabilities, and a __json__ protocol (allowing one to return an already serialized string, with quotes, if needed, included in the serialization) seems to be good way to go. There is no need to change Python object for including a "__json__" slot - it is just Python's json encoder (and 3rd parties) that would need to check for that.
I am here calling that we settle for that - (I think this would need a PEP, right?) .
ChrisA _______________________________________________ Python-ideas mailing list -- email@example.com To unsubscribe send an email to firstname.lastname@example.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://email@example.com/message/4KXUIV... Code of Conduct: http://python.org/psf/codeofconduct/