如何限制JSONEncoder产生的浮点数的数量?

发布于 2021-01-29 14:58:05

我正在尝试设置pythonjson库,以便将包含其他字典作为元素的字典保存到文件中。浮点数很多,我想将位数限制为例如7

根据其他职位,encoder.FLOAT_REPR应使用SO 。但是,它不起作用。

例如,下面的代码在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()

我该如何解决?

可能无关紧要,但我在macOS上。

编辑

该问题被标记为重复。但是,在原始帖子的已接受答案(到目前为止是唯一的答案)中明确指出:

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

因此,该解决方案不是正确的解决方案。另外,它使用的是库simplejson 而不是json

关注者
0
被浏览
74
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    选项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))
    

    输出test.json如下:

    {
        "val": 5.7868688,
        "name": "kjbkjbkj",
        "mylist": [
            1.2345679,
            12,
            1.23,
            {
                "foo": "a",
                "bar": 9.8765432
            }
        ],
        "mydict": {
            "bar": "b",
            "foo": 1.9283747
        }
    }
    

    此方法的局限性在于它也将匹配双引号内的数字(以字符串表示的浮点数)。您可以根据自己的需要提出一个限制性更强的正则表达式来处理此问题。

    选项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
    

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

    with open('test.json', 'w') as f:
        json.dump(d, f, cls = MyCustomEncoder)
    

    输出文件test.json

    {"val": 5.7868688, "name": "kjbkjbkj", "mylist": [1.2345679, 12, 1.2300000, {"foo": "a", "bar": 9.8765432}], "mydict": {"bar": "b", "foo": 1.9283747}}
    

    为了使其他关键字参数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)
    

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看