Object of type Decimal is not JSON serializable

小灰灰 2023-03-01 11:43 62阅读 0赞

json遇到Decimal 型数据无法正确处理

解决方案

  1. import json
  2. result = [
  3. { 'name': '小红', 'age': 26, 'balance': decimal.Decimal(21.56)},
  4. { 'name': '小明', 'age': 24, 'balance': decimal.Decimal(31.23)},
  5. ]
  6. class DecimalEncoder(json.JSONEncoder):
  7. def default(self, o):
  8. if isinstance(o, decimal.Decimal):
  9. return float(o)
  10. super(DecimalEncoder, self).default(o)
  11. # jsonData是结合上下文自己定义的
  12. # ensure_ascii=False,显示中文
  13. result = json.dumps(result, cls=DecimalEncoder, ensure_ascii=False)
  14. print(result)

发表评论

表情:
评论列表 (有 0 条评论,62人围观)

还没有评论,来说两句吧...

相关阅读