Python JSON serialize a Decimal object

后端 未结 17 1174
星月不相逢
星月不相逢 2020-11-22 08:27

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

17条回答
  •  情深已故
    2020-11-22 09:10

    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)
    

提交回复
热议问题