How to convert Decimal("123456789012345.99")
to json number 123456789012345.99?
Python 3.11 win64
import json
from decimal import Decimal
class DecimalToFloat(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
class DecimalToStr(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return str(obj)
return json.JSONEncoder.default(self, obj)
obj = {'decimal':Decimal("123456789012345.99")}
# {"decimal": 123456789012345.98} - WRONG!!!!
print(json.dumps(obj, cls=DecimalToFloat))
# {"decimal": "123456789012345.99"} - json string
print(json.dumps(obj, cls=DecimalToStr))
# ??? {"decimal": 123456789012345.99}
UPD
simplejson module is OK
# {"decimal": 123456789012345.99}
print(simplejson.dumps(obj, use_decimal=True))
Is there a way to do the same with the standard library without external dependencies?