[Python - Error] Object of type Decimal is not JSON serializable

json遇到Decimal 型数据无法正确处理
解决方案
import json

result = [
{'name': '小红', 'age': 26, 'balance': decimal.Decimal(21.56)},
{'name': '小明', 'age': 24, 'balance': decimal.Decimal(31.23)},
]
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o)
super(DecimalEncoder, self).default(o)

# jsonData是结合上下文自己定义的
# ensure_ascii=False,显示中文
result = json.dumps(result, cls=DecimalEncoder, ensure_ascii=False)
print(result)

 

posted @ 2021-11-26 23:17  决明子~  阅读(540)  评论(0编辑  收藏  举报