这是一个将浮点值转换为字符串的简单 JSON 编码器:
class NestedEncoder(json.JSONEncoder):
'''
A JSON Encoder that converts floats/decimals to strings and allows nested objects
'''
def default(self, obj):
if isinstance(obj, float) or obj.__class__.__name__ == "float32":
return self.floattostr(obj)
elif obj.__class__.__name__ == "type":
return str(obj)
elif hasattr(obj, 'repr_json'):
return obj.repr_json()
else:
return json.JSONEncoder.default(self, obj)
def floattostr(self,o,_inf=float('Inf'), _neginf=-float('-Inf'),nan_str="None"):
if o != o:
text = nan_str
elif o == _inf:
text = 'Infinity'
elif o == _neginf:
text = '-Infinity'
else:
return o.__repr__()
return text
现在有两个测试。第一个创建一个 Infinity 值的 float 并使用自定义编码器对其进行编码。测试通过。
def test_inf():
inf = float('Inf')
as_json = json.dumps(inf,cls=NestedEncoder)
assert as_json == "Infinity"
第二个测试做同样的事情,但将 float 放入字典中:
def test_inf_dic():
inf = float('Inf')
as_json = json.dumps({'key':inf},cls=NestedEncoder)
assert as_json == "{'key':'Infinity'}"
输出:
=================================== FAILURES ===================================
_________________________________ test_inf_dic _________________________________
def test_inf_dic():
inf = float('Inf')
as_json = json.dumps({'key':inf},cls=NestedEncoder)
> assert as_json == "{'key':'Infinity'}"
E assert '{"key": Infinity}' == "{'key':'Infinity'}"
E - {"key": Infinity}
E ? ^ ^ ^
E + {'key':'Infinity'}
E ? ^ ^ ^ +
编辑:
自定义编码器只会在第一次测试时被调用,第二次不会被调用。
最佳答案
您说得对,您的自定义函数在测试期间没有被调用。文档中解释了这样做的原因:
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError. If not specified, TypeError is raised.
因为 float
是一个它已经知道如何序列化的对象,所以它不会被调用。对于 float
序列化,您可以覆盖 encode
函数。
关于python - 使用自定义 python JSON 编码器在字典中编码 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47276152/