On Aug 8, 2019, at 13:43, __pete...@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.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@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/UBMDFBPQC7KEJBEPXQQXKXSHLXFSHYHH/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to