【发布时间】:2017-09-26 11:57:12
【问题描述】:
我之前问过这个问题,它被标记为与this 重复,但是接受的答案不起作用,甚至 pylint 显示代码中有错误。
我想做什么:
from decimal import Decimal
import json
thang = {
'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
'Count': 2}
print(json.dumps(thang))
这会引发:
TypeError: Object of type 'Decimal' is not JSON serializable
所以我尝试了链接的answer:
from decimal import Decimal
import json
thang = {
'Items': [{'contact_id': Decimal('2'), 'street_name': 'Asdasd'}, {'contact_id': Decimal('1'), 'name': 'Lukas', 'customer_id': Decimal('1')}],
'Count': 2}
class DecimalEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
if isinstance(o, 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)
print(json.dumps(thang, cls=DecimalEncoder))
这里 linter 显示 return super(DecimalEncoder, self)._iterencode(o, markers) 行有错误,因为 Super of 'DecimalEncoder' has no '_iterencode' member 和运行时抛出
TypeError: Object of type 'Decimal' is not JSON serializable
我该如何进行这项工作?
【问题讨论】:
标签: python json python-3.x serialization