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`).
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).