python - TypeError:Decimal 类型的对象不是 JSON 可序列化的
问题描述
TypeError: Object of type Decimal is not JSON serializable
当我在其中运行时,postman api
我收到上述错误,因为sales_qty
是十进制,我不知道如何decimal
在for
循环中解析并将其作为 json 返回
from flask import Flask, jsonify
import decimal,json
result= [('V_M_001', 'KITE', 'Napkin', 1, 2, 12, 0, Decimal('0'), Decimal('0'), Decimal('0'), Decimal('0')),
('V_M_001', 'KITE', 'Napkin', 2, 4, 34, 5, Decimal('1'), Decimal('4'), Decimal('0'), Decimal('0'))]
def fun():
for i in result:
data_all.append({
"machine_name":i.machine_name,
"location":i.location,
"item_name":i.item_name,
"row_no":i.row_no,
"require_minimum_stk_qty":i.require_minimum_stk_qty,
"capacity":i.capacity,
"stock_qty":i.stock_qty,
"sales_qty":i.sales_qty,
"available_qty":i.available_qty,
"sales_day_qty":i.sales_day_qty,
"sales_week_qty":i.sales_week_qty
})
return jsonify(data_all)
fun()
输出:
TypeError: Object of type Decimal is not JSON serializable
解决方案
使用带有 cls 参数的 json.dump,我相信当 json 模块不知道如何转换时,它会调用默认函数。
import json
import decimal
class Encoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, decimal.Decimal): return float(obj)
json.dumps( ... , cls = Encoder)
```python
推荐阅读
- angular - 为传单执行 L.tileLayer.wms 时向选项添加 env
- c++ - 如何在不使用条件语句的情况下打印横向金字塔?
- amazon-web-services - ng 构建在 AWS 中出现“Javascript 堆内存不足”的 codeBuild 失败
- augmented-reality - Magic Leap Lumin 运行时编辑器无法在 macOS BigSur 上打开
- apache - 尝试通过 .htaccess 将页面从旧域重定向到新域
- sql - 如何在 SQL 中计算逗号分隔列表中的字符串项
- python-3.x - 使用 Python 多处理库和非守护进程嵌套进程,我如何检测父进程的停止/死亡?
- r - R中的动画直方图
- angular - 另一个 RXJS “ERROR TypeError: Object(...) is not a function”问题
- django - 使用登录的用户名作为 pk 进行 django 更新