我将以下简单有效的JSON对象保存到我的Django应用程序中的模型中:
{
"start_date": 1311471044.24338
"post_count": 25
}
该模型如下所示:
from django.db import models
from django_extensions.db.fields import json as json
class UserProfile(models.Model):
data = json.JSONField()
要阅读发布的数据,我基本上都是
posted_data = request.FILES.get('posted_data').read()
json_data = simplejson.loads(posted_data)
然后数据包含expect类型(float)
logging.debug( "start_date type: " + str(type(json_data.get('start_date'))))
logging.debug( "post_count type: " + str(type(json_data.get('post_count'))))
>> 2011-07-24 10:03:01,636 DEBUG start_date type: <type 'float'>
>> 2011-07-24 10:03:01,636 DEBUG post_count type: <type 'int'>
然后我保存这样的数据:
user_profile.data = json_data
user_profile.save()
然后我读回数据,整数很好,但引用了浮点数,例如:
print user_profile.data
{
"post_count : 25
"start_date": "1311471044.24338"
}
如何防止浮点数被不必要地转换为字符串?
修改
可能在这里找到了解释:Rails JSON Serialization of Decimal adds Quotes
我仍然会对其他解释感兴趣。
答案 0 :(得分:1)
This answer似乎是最好的解释:
将小数字从A语言移到语言B的唯一“安全”方法是使用String。如果你的json包含“rating”:98.79999999999999它可能会被你的JavaScript运行时转换为98.79999999999998。