我正在尝试设置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()
我怎么解决这个问题?
它可能无关紧要,但我在OSX上。
编辑
这个问题被标记为重复。然而在the accepted answer (and until now the only one) to the original post中明确指出:
注意:此解决方案不适用于python 3.6+
所以解决方案不合适。此外,它使用库simplejson
而不是库json
。
您可以使用json.dumps
将对象转储到字符串,然后使用this post上显示的技术查找并舍入浮点数。
为了测试它,我在你提供的示例的顶部添加了一些更复杂的嵌套结构::
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
}
}
此方法的一个限制是它还将匹配双引号内的数字(浮点数表示为字符串)。根据您的需要,您可以提出一个更严格的正则表达式来处理这个问题。
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中显示的相同。
根据我对问题的回答,您可以使用以下内容:
Write two-dimensional list to JSON file。
我说可能是因为它需要在使用dump()
对JSON进行编码之前将所有浮点值“包装”在Python字典(或列表)中。
(使用Python 3.7.2测试。)
from _ctypes import PyObj_FromPtr
import json
import re
class FloatWrapper(object):
""" Float value wrapper. """
def __init__(self, value):
self.value = value
class MyEncoder(json.JSONEncoder):
FORMAT_SPEC = '@@{}@@'
regex = re.compile(FORMAT_SPEC.format(r'(\d+)')) # regex: r'@@(\d+)@@'
def default(self, obj):
return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, FloatWrapper)
else super(MyEncoder, self).default(obj))
def iterencode(self, obj, **kwargs):
for encoded in super(MyEncoder, self).iterencode(obj, **kwargs):
# Check for marked-up float values (FloatWrapper instances).
match = self.regex.search(encoded)
if match: # Get FloatWrapper instance.
id = int(match.group(1))
float_wrapper = PyObj_FromPtr(id)
json_obj_repr = '%.7f' % float_wrapper.value # Create alt repr.
encoded = encoded.replace(
'"{}"'.format(self.FORMAT_SPEC.format(id)), json_obj_repr)
yield encoded
d = dict()
d['val'] = FloatWrapper(5.78686876876089075543) # Must wrap float values.
d['name'] = 'kjbkjbkj'
with open('float_test.json', 'w') as file:
json.dump(d, file, cls=MyEncoder, indent=4)
创建的文件内容:
{
"val": 5.7868688,
"name": "kjbkjbkj"
}
更新:
正如我所提到的,上面要求在调用float
之前包装所有json.dump()
值。幸运的是,通过添加和使用以下(经过最少测试的)实用程序可以实现自动化:
def wrap_type(obj, kind, wrapper):
""" Recursively wrap instances of type kind in dictionary and list
objects.
"""
if isinstance(obj, dict):
new_dict = {}
for key, value in obj.items():
if not isinstance(value, (dict, list)):
new_dict[key] = wrapper(value) if isinstance(value, kind) else value
else:
new_dict[key] = wrap_type(value, kind, wrapper)
return new_dict
elif isinstance(obj, list):
new_list = []
for value in obj:
if not isinstance(value, (dict, list)):
new_list.append(wrapper(value) if isinstance(value, kind) else value)
else:
new_list.append(wrap_type(value, kind, wrapper))
return new_list
else:
return obj
d = dict()
d['val'] = 5.78686876876089075543
d['name'] = 'kjbkjbkj'
with open('float_test.json', 'w') as file:
json.dump(wrap_type(d, float, FloatWrapper), file, cls=MyEncoder, indent=4)
不回答这个问题,但对于解码方面,你可以做这样的事情,或者覆盖钩子方法。
用这种方法解决这个问题虽然需要编码,解码,然后再次编码,这是过度复杂的,不再是最好的选择。我假设Encode有Decode所做的所有钟声和口哨,我的错误。
# d = dict()
class Round7FloatEncoder(json.JSONEncoder):
def iterencode(self, obj):
if isinstance(obj, float):
yield format(obj, '.7f')
with open('test.json', 'w') as f:
json.dump(d, f, cls=Round7FloatEncoder)
您可以使用字符串格式函数将您的数字转换为只有7个小数点的字符串。然后将它转换回如下的浮点数:
float("{:.7f}".format(5.78686876876089075543))
字符串中的括号,直到它需要遵循规则内部的格式。
冒号启动格式规则。
7
告诉编队者人在小数点后如何离开。
并且f
表示格式化浮点数。
然后将您的数字传递给格式函数,该函数返回:'5.7868688'
然后您可以将其传递回float函数以使其返回。
在这里查看有关python中的格式函数的更多信息:https://pyformat.info/