I have a Decimal('3.9')
as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}
. I don't care about precision on the client side, so a float is fine.
Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999}
which is wrong, and will be a big waste of bandwidth.
this can be done by adding
in
\Lib\json\encoder.py:JSONEncoder._iterencode
, but I was hoping for a better solution3.9
can not be exactly represented in IEEE floats, it will always come as3.8999999999999999
, e.g. tryprint repr(3.9)
, you can read more about it here:http://en.wikipedia.org/wiki/Floating_point
http://docs.sun.com/source/806-3568/ncg_goldberg.html
So if you don't want float, only option you have to send it as string, and to allow automatic conversion of decimal objects to JSON, do something like this: