TypeError: Object of type Decimal is not JSON serializable(TypeError:类型为Decimal的对象不可JSON序列化)
本文介绍了TypeError:类型为Decimal的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TypeError: Object of type Decimal is not JSON serializable
我在postman api中运行时收到上述错误,因为sales_qty是小数,我不知道如何在for循环中解析decimal并将其作为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.ump,我相信当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
这篇关于TypeError:类型为Decimal的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:TypeError:类型为Decimal的对象不可JSON序列化
基础教程推荐
猜你喜欢
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 求两个直方图的卷积 2022-01-01
