On Fri, 9 Aug 2019 at 14:49, Richard Musil <risa2000x@gmail.com> wrote:
Joao S. O. Bueno wrote:
However, as noted, there is no way to customize Python JSON encoder to encode an arbitrary decimal number in JSON, even though the standard does allow it, and Python supports then via decimal.Decimal. Short of a long term solution, like a __json__ protocol, or at least special support in Python json module for objects of type "numbers.Number", the only way to go, is, as you are asking, being able to insert "raw strings into json".
Would the approach I outlined in my answer to Dominik be acceptable?:
1) Add keyword argument to `json.dump(s)` called `dump_float` which will act as a counter part to `parse_float` keyword argument in `json.load(s)`. The argument will accept custom type (class) for the user's "float" representation (for example `decimal.Decimal`).
yes, just that it should be called `dump_as_float` and take either a class or a tuple-of-classes (or maybe just another argument that when set to "True" would work for any object for which isinstance(obj, numbers.Number) is True)
2) If specified by the client code, JSONEncoder, when identifying object of that type in the input data will encode it using the special rule suggested by Dominik: ``` # if o is custom float type if isinstance(o, <dump_float Type>): dump_val = str(o) try: float(dump_val) except ValueError: raise TypeError('... is not JSON serializable float number') from None <write dump_val to the stream> ``` This would have following implications/consequences: 1) str(o) may return invalid float, but the check will not let it into the stream. 2) the contract between the custom float class implementation and standard `json` module will be pretty clear - it must implement the serialization in its __str__ function and must return valid float. 3) the standard implementation does not need to `import decimal`. If the client code needs this feature, it will `import decimal` itself. 4) definition which class/type objects should be handled by this rule will be pretty clear, it will be the only one specified in `dump_float` argument (if specified at all).
Yes, but I don know if the reverse float checking is over-policying it - it is not the role of the language or its libraries to prevent any way that the JSON encoded string is valid-json. So, maybe emitting a warning there, but raising TypeError will only make someone intending to encode numbers in Hexadecimal in her custom JSON to pop here crying tomorrow.
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/7HCLSK... Code of Conduct: http://python.org/psf/codeofconduct/