格式浮动与标准 json 模块 [英] Format floats with standard json module

查看:26
本文介绍了格式浮动与标准 json 模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 2.6 中使用标准 json 模块 来序列化浮点数列表.但是,我得到了这样的结果:

<预><代码>>>>导入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]'

我尝试定义自己的 JSON Encoder 类:

class MyEncoder(json.JSONEncoder):定义编码(自我,对象):如果 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 模块.

我怎样才能做到这一点?

解决方案

注意:这在任何最新版本的 Python 中工作.

不幸的是,我认为您必须通过猴子补丁来做到这一点(在我看来,这表明标准库 json 包中存在设计缺陷).例如,这段代码:

导入json从 json 导入编码器编码器.FLOAT_REPR = lambda o: 格式(o, '.2f')打印(json.dumps(23.67))打印(json.dumps([23.67, 23.97, 23.87]))

发射:

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?

解决方案

Note: This does not work in any recent version of Python.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆