Python JSON serialize a Decimal object

后端 未结 17 1159
星月不相逢
星月不相逢 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:28

    The native option is missing so I'll add it for the next guy/gall that looks for it.

    Starting on Django 1.7.x there is a built-in DjangoJSONEncoder that you can get it from django.core.serializers.json.

    import json
    from django.core.serializers.json import DjangoJSONEncoder
    from django.forms.models import model_to_dict
    
    model_instance = YourModel.object.first()
    model_dict = model_to_dict(model_instance)
    
    json.dumps(model_dict, cls=DjangoJSONEncoder)
    

    Presto!

提交回复
热议问题