想通过Json输出一个嵌套的字典数据数据结构,其中的浮点数位数比较长,找不到合适的方法对小数点之后数字进行截断。
数据结构示例:
import json
from json import encoder
data = {
"branch": "xxxx",
"date": "2022-11-10",
"achv": 10759.900000000001
}
class MyEncoder(json.JSONEncoder):
def encode(self, obj):
if isinstance(obj, float):
return format(obj, '.1f')
return json.JSONEncoder.encode(self, obj)
json_str = json.dumps(data, cls=MyEncoder)
print(json_str)
# 输出
# {"branch": "xxxx", "date": "2022-11-10", "achv": 10759.900000000001}
下面的链接中都提到了这个问题,但没有彻底解决。
参考链接:
本文介绍了一种在Python中使用自定义编码器类来控制JSON输出中小数点后位数的方法。通过重写JSONEncoder的encode方法实现对浮点数的格式化,解决了输出JSON时浮点数位数过长的问题。
1107

被折叠的 条评论
为什么被折叠?



