问题描述
我从一个十进制数值的DB中拉一个总和。我试图在JSON结果中使用该值
json.dumps({'sum':amount })#where amount is my Decimal
Django无法序列化 Decimal
。
我可以将其转换为字符串,但我想在JSON中使用数字类型。
如果我尝试将其转换为一个 float
,最终会超过2位小数。
如果可能,要得到如下结果,需要做什么?
{'sum':500.50}
你可以做的是扩展JSONDecoder类来提供自定义十进制类型的序列化器,与本文档中的示例类似:
>>> import json
>>> class DecimalEncoder(json.JSONEncoder):
... def default(self,obj):
... if isinstance(obj,Decimal):
... return%.2f %obj
... return json.JSONEncoder.default(self,obj)
...
这是一个非常实用的例子,如何做,希望是一个很好的起点。
I'm pulling a sum from a DB which is a decimal value.I'm trying to use that value in a JSON result
json.dumps( { 'sum': amount } ) #where amount is my Decimal
Django can't serialize the Decimal
.I can convert it to a string, but I'd like a numeric type within the JSON.If I try and convert it to a float
I end up with more than 2 decimal places.
What needs to happen, if possible, to get a result like the following?
{ 'sum': 500.50 }
What you can do is extend the JSONDecoder class to provide a custom serializer for the Decimal type, similar to the example in this document: http://docs.python.org/py3k/library/json.html
>>> import json
>>> class DecimalEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, Decimal):
... return "%.2f" % obj
... return json.JSONEncoder.default(self, obj)
...
That's a nonworking example of how to do it, hopefully a good starting point for you.
这篇关于十进制到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!