选项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中所示的相同。



