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 p
For Django users:
Recently came across TypeError: Decimal('2337.00') is not JSON serializable
while JSON encoding i.e. json.dumps(data)
Solution:
# converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder
json.dumps(response.data, cls=DjangoJSONEncoder)
But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float
option in json.loads
:
import decimal
data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)