LEATH
子类如何?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
Simplejson 2.1而更高的公司则支持十进制类型:>>> 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'希望这个特性将包含在标准库中。