栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

您可以使用转储对象的字符串

json.dumps
,然后使用上显示的技术,这个帖子找到和圆你的浮点数。

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

d = dict()d['val'] = 5.78686876876089075543d['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 stringd_string = json.dumps(d, indent=4)# find numbers with 8 or more digits after the decimal pointpat = re.compile(r"d+.d{8,}")def mround(match):    return "{:.7f}".format(float(match.group()))# write the modified string to a filewith 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.JSONEnprer

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

import jsonclass MyCustomEnprer(json.JSONEnprer):    def iterenpre(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 MyCustomEnprer.iterenpre(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 MyCustomEnprer.iterenpre(self, o):         yield chunk     if i != last_index:          yield ", " yield "]"        else: for chunk in json.JSONEnprer.iterenpre(self, obj):     yield chunk

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

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

输出文件

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 enprerwith open('test.json', 'w') as f:    json.dump(d, f, cls = MyCustomEnprer)# load output into new_dwith open('test.json', 'r') as f:    new_d = json.load(f)# write new_d out using default enprerwith open('test.json', 'w') as f:    json.dump(new_d, f, indent=4)

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/429271.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号