2011-07-24 17 views
2

我节省了下面的简单,有效的JSON对象在我的Django应用程序的模型:Django JSONField将浮点值编码为字符串?

{ 
    "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) 

然后,数据包含期望类型(浮点)

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

,我仍然有兴趣在其他的解释,但。

回答

1

This answer似乎是最好的解释:

唯一的“安全”的方式,从手语A到B语言小数是使用字符串。如果你的json包含“rating”:98.79999999999999它可能会被JavaScript运行时转换为98.79999999999998。

+0

你也可以打破组成部分和小数部分为两个整数字段。 – abellina

+0

将数字分解为两个整数字段使得API变得丑陋,并且通常在正常的生产系统中永远不会完成。 – Centurion