格式浮动与标准的JSON模块 [英] Format floats with standard json module
问题描述
我使用python 2.6中的标准 json模块来序列化浮动列表。然而,我得到的结果是这样的:
>>> import json
>>> json.dumps([23.67,23.97,23.87])
'[23.670000000000002,23.969999999999999,23.870000000000001]'
我希望浮点数只有两位十进制数字。输出应该如下所示:
>>> json.dumps([23.67,23.97,23.87])
'[23.67,23.97,23.87]'
$ b $我已经尝试定义我自己的JSON编码器类:
$ b $ pre $ MyEncoder(json.JSONEncoder):
def encode(self,obj):
if isinstance(obj,float):
返回格式(obj,'.2f')
返回json.JSONEncoder.encode(self,obj)
这适用于唯一的浮动对象:
>>> json.dumps(23.67,cls = MyEncoder)
'23 .67'
但嵌套失败对象:
>>> json.dumps([23.67,23.97,23.87])
'[23.670000000000002,23.969999999999999,23.870000000000001]'
我不想有外部的依赖关系,所以我宁愿坚持使用标准的json模块。
我怎么能做到这一点?
不幸的是,我相信你必须通过猴子修补(这在我看来,标志着一个设计缺陷 json
package)。例如,这段代码:
从json导入编码器导入json
encoder.FLOAT_REPR = lambda o: format(o,'.2f')
print json.dumps(23.67)
print json.dumps([23.67,23.97,23.87])
$ c $
$ b 发出:
23.67
[23.67,23.97,23.87]
显然,应该有一个架构的方法来覆盖 FLOAT_REPR
,这样如果你愿意的话,浮点数的每一个表示都在你的控制之下。但不幸的是,这不是如何设计 json
包的: - (。
)
I am using the standard json module in python 2.6 to serialize a list of floats. However, I'm getting results like this:
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
I want the floats to be formated with only two decimal digits. The output should look like this:
>>> json.dumps([23.67, 23.97, 23.87])
'[23.67, 23.97, 23.87]'
I have tried defining my own JSON Encoder class:
class MyEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, float):
return format(obj, '.2f')
return json.JSONEncoder.encode(self, obj)
This works for a sole float object:
>>> json.dumps(23.67, cls=MyEncoder)
'23.67'
But fails for nested objects:
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
I don't want to have external dependencies, so I prefer to stick with the standard json module.
How can I achieve this?
解决方案 Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library json
package). E.g., this code:
import json
from json import encoder
encoder.FLOAT_REPR = lambda o: format(o, '.2f')
print json.dumps(23.67)
print json.dumps([23.67, 23.97, 23.87])
emits:
23.67
[23.67, 23.97, 23.87]
as you desire. Obviously, there should be an architected way to override FLOAT_REPR
so that EVERY representation of a float is under your control if you wish it to be; but unfortunately that's not how the json
package was designed:-(.
这篇关于格式浮动与标准的JSON模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!