首页 > 技术文章 > Object of type Decimal is not JSON serializable

qsxbc 2020-07-24 17:13 原文

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)

推荐阅读