如何设置JSONEncoder生成的浮点数?

Fra*_*Boi 6 python floating-point json python-3.x

我正在尝试设置python json库以保存为包含其他词典元素的字典.有许多浮点数,我想限制位数,例如7.

根据SO中的其他帖子,encoder.FLOAT_REPR如果它不起作用将被使用.

例如,以下在Python3.7.1中运行的代码打印所有数字:

import json
json.encoder.FLOAT_REPR = lambda o: format(o, '.7f' )
d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
f = open('test.json', 'w')
json.dump(d, f, indent=4)
f.close()
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

它可能无关紧要,但我在OSX上.

编辑

这个问题被标记为重复.然而,在原始的接受(并且直到现在唯一)答案中,明确说明:

注意:此解决方案不适用于python 3.6+

所以解决方案不合适.此外,它使用的是库simplejson 而不是json.

pro*_*ski 10

在 Python 3 中仍然可以进行猴子补丁json,但是FLOAT_REPR您需要修改float. 确保c_make_encoder像在 Python 2 中一样禁用。

import json

class RoundingFloat(float):
    __repr__ = staticmethod(lambda x: format(x, '.2f'))

json.encoder.c_make_encoder = None
if hasattr(json.encoder, 'FLOAT_REPR'):
    # Python 2
    json.encoder.FLOAT_REPR = RoundingFloat.__repr__
else:
    # Python 3
    json.encoder.float = RoundingFloat

print(json.dumps({'number': 1.0 / 81}))
Run Code Online (Sandbox Code Playgroud)

优点:简单,可以进行其他格式设置(例如科学记数法、去除尾随零等)。缺点:它看起来比实际更危险。


pau*_*ult 5

选项 1:使用正则表达式匹配来舍入。

您可以使用转储对象的字符串json.dumps,然后使用上显示的技术,这个帖子找到和圆你的浮点数。

为了测试它,我在您提供的示例之上添加了一些更复杂的嵌套结构:

d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
d["mylist"] = [1.23456789, 12, 1.23, {"foo": "a", "bar": 9.87654321}]
d["mydict"] = {"bar": "b", "foo": 1.92837465}

# dump the object to a string
d_string = json.dumps(d, indent=4)

# find numbers with 8 or more digits after the decimal point
pat = re.compile(r"\d+\.\d{8,}")
def mround(match):
    return "{:.7f}".format(float(match.group()))

# write the modified string to a file
with open('test.json', 'w') as f:
    f.write(re.sub(pat, mround, d_string))
Run Code Online (Sandbox Code Playgroud)

输出test.json看起来像:

d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
d["mylist"] = [1.23456789, 12, 1.23, {"foo": "a", "bar": 9.87654321}]
d["mydict"] = {"bar": "b", "foo": 1.92837465}

# dump the object to a string
d_string = json.dumps(d, indent=4)

# find numbers with 8 or more digits after the decimal point
pat = re.compile(r"\d+\.\d{8,}")
def mround(match):
    return "{:.7f}".format(float(match.group()))

# write the modified string to a file
with open('test.json', 'w') as f:
    f.write(re.sub(pat, mround, d_string))
Run Code Online (Sandbox Code Playgroud)

此方法的一个限制是它还会匹配双引号内的数字(表示为字符串的浮点数)。根据您的需要,您可以想出一个更严格的正则表达式来处理这个问题。

选项 2:子类 json.JSONEncoder

以下是适用于您的示例并处理您将遇到的大多数边缘情况的内容:

import json

class MyCustomEncoder(json.JSONEncoder):
    def iterencode(self, obj):
        if isinstance(obj, float):
            yield format(obj, '.7f')
        elif isinstance(obj, dict):
            last_index = len(obj) - 1
            yield '{'
            i = 0
            for key, value in obj.items():
                yield '"' + key + '": '
                for chunk in MyCustomEncoder.iterencode(self, value):
                    yield chunk
                if i != last_index:
                    yield ", "
                i+=1
            yield '}'
        elif isinstance(obj, list):
            last_index = len(obj) - 1
            yield "["
            for i, o in enumerate(obj):
                for chunk in MyCustomEncoder.iterencode(self, o):
                    yield chunk
                if i != last_index: 
                    yield ", "
            yield "]"
        else:
            for chunk in json.JSONEncoder.iterencode(self, obj):
                yield chunk
Run Code Online (Sandbox Code Playgroud)

现在使用自定义编码器写入文件。

with open('test.json', 'w') as f:
    json.dump(d, f, cls = MyCustomEncoder)
Run Code Online (Sandbox Code Playgroud)

输出文件test.json

{"val": 5.7868688, "name": "kjbkjbkj", "mylist": [1.2345679, 12, 1.2300000, {"foo": "a", "bar": 9.8765432}], "mydict": {"bar": "b", "foo": 1.9283747}}
Run Code Online (Sandbox Code Playgroud)

为了让其他关键字参数indent起作用,最简单的方法是读入刚刚写入的文件,然后使用默认编码器将其写回:

# write d using custom encoder
with open('test.json', 'w') as f:
    json.dump(d, f, cls = MyCustomEncoder)

# load output into new_d
with open('test.json', 'r') as f:
    new_d = json.load(f)

# write new_d out using default encoder
with open('test.json', 'w') as f:
    json.dump(new_d, f, indent=4)
Run Code Online (Sandbox Code Playgroud)

现在输出文件与选项 1 中显示的相同。