On Aug 8, 2019, at 13:43, __peter__@web.de wrote:
You have overwritten the wrong method:
Unfortunately, he hasn’t. Overriding encode isn’t particularly useful.
$ cat demo.py import io import json import decimal
class DecimalEncoder(json.JSONEncoder): def encode(self, o): if isinstance(o, decimal.Decimal): return str(o) return super().encode(o)
input = "0.6441726684570313" obj = json.loads(input, parse_float=decimal.Decimal) output = json.dumps(obj, cls=DecimalEncoder) assert input == output
Try it with: input = ["0.6441726684570313"] You’ll get a TypeError because Decimal isn’t serializable. The encode method doesn’t get called recursively; instead, a function gets created that calls itself recursively, and encode calls that. So, any hooks you add in encode only affect the top-level value, not values inside arrays or objects.