PythonJSON序列化一个Decimal对象我有一个Decimal('3.9')作为对象的一部分,并希望将其编码为JSON字符串,该字符串应该如下所示{'x': 3.9}..我不关心客户端的精确性,所以浮点数是可以的。有什么好的方法来序列化这个吗?JSONDecoder不接受Decimal对象,并提前转换为浮点数{'x': 3.8999999999999999}这是错误的,而且将是对带宽的极大浪费。
3 回答

LEATH
TA贡献1936条经验 获得超6个赞
json.JSONEncoder
?
class DecimalEncoder(json.JSONEncoder): def _iterencode(self, o, markers=None): if isinstance(o, decimal.Decimal): # wanted a simple yield str(o) in the next line, # but that would mean a yield on the line with super(...), # which wouldn't work (see my comment below), so... return (str(o) for o in [o]) return super(DecimalEncoder, self)._iterencode(o, markers)
json.dumps({'x': decimal.Decimal('5.5')}, cls=DecimalEncoder)

德玛西亚99
TA贡献1770条经验 获得超3个赞
>>> 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'

饮歌长啸
TA贡献1951条经验 获得超3个赞
class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): return float(o) return super(DecimalEncoder, self).default(o)
添加回答
举报
0/150
提交
取消