On Fri, Aug 9, 2019 at 5:06 AM Richard Musil <risa2000x@gmail.com> wrote:
I am not sure `(str(o),)` is what I want. For a comparison here are three examples: ``` json:orig = {"val": 0.6441726684570313} json:pyth = {'val': 0.6441726684570312} json:seri = {"val": 0.6441726684570312}
dson:orig = {"val": 0.6441726684570313} dson:pyth = {'val': Decimal('0.6441726684570313')} dson:seri = {"val": ["0.6441726684570313"]}
sjson:orig = {"val": 0.6441726684570313} sjson:pyth = {'val': Decimal('0.6441726684570313')} sjson:seri = {"val": 0.6441726684570313} ``` Each one has three outputs, `orig` is the input text, `pyth` is its python representation in a `dict`, `seri` is the serialized text output of `pyth`.
Now, the prefixes are `json` for standard Python module (which gets the last digit different from the output). `dson` is standard Python module using `parse_float=decimal.Decimal` on `json.loads` and custom serializer with proposed `return (str(o),)`. Finally `sjson` is `simplejson` using `use_decimal=True` on `json.loads` and the same (which is default) on its `json.dumps`.
A quick search of bpo showed up this thread: https://bugs.python.org/issue16535 Unfortunately, the trick given doesn't work, as there have been some optimizations done that break it. There are two broad suggestions that came out of that thread and others, and I think it may be worth reopening them. 1) Should JSONEncoder (the class underlying json.dumps) natively support decimal.Decimal, and if so, can it avoid importing that module unnecessarily? 2) Should there be a protocol obj.__json__() to return a string representation of an object for direct insertion into a JSON file? I'm inclined towards the protocol, since there are protocols for various other encoders (eg deepcopy, pickle), and it avoids the problem of json importing decimal. It can also be implemented entirely as a third-party patch, although you'd need to subclass Decimal to add that method. 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. ChrisA