我有一个 Decimal('3.9')
作为对象的一部分,并希望将其编码为 JSON 字符串,该字符串应类似于 {'x': 3.9}
.我不关心客户端的精度,所以 float 就可以了。
请问有什么好的方法可以连载吗? JSONDecoder 不接受 Decimal 对象,并且事先转换为 float 会产生 {'x': 3.8999999999999999}
这是错误的,并且会极大地浪费带宽。
最佳答案
Simplejson 2.1及更高版本原生支持 Decimal 类型:
>>> json.dumps(Decimal('3.9'), use_decimal=True)
'3.9'
请注意 use_decimal
默认为 True
:
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True,
bigint_as_string=False, sort_keys=False, item_sort_key=None,
for_json=False, ignore_nan=False, **kw):
所以:
>>> json.dumps(Decimal('3.9'))
'3.9'
希望这个特性将包含在标准库中。
关于Python JSON 序列化一个 Decimal 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59139712/