PythonJSON序列化一個Decimal對象我有一個Decimal('3.9')作為對象的一部分,并希望將其編碼為JSON字符串,該字符串應該如下所示{'x': 3.9}..我不關心客戶端的精確性,所以浮點數(shù)是可以的。有什么好的方法來序列化這個嗎?JSONDecoder不接受Decimal對象,并提前轉換為浮點數(shù){'x': 3.8999999999999999}這是錯誤的,而且將是對帶寬的極大浪費。
3 回答
LEATH
TA貢獻1936條經(jīng)驗 獲得超7個贊
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條經(jīng)驗 獲得超3個贊
>>> json.dumps(Decimal('3.9'), use_decimal=True)'3.9'use_decimalTrue
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條經(jīng)驗 獲得超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
提交
取消
