gpt4 book ai didi

python - 类型错误 : Object of type Decimal is not JSON serializable

转载 作者:行者123 更新时间:2023-12-05 08:49:01 27 4
gpt4 key购买 nike

TypeError: Decimal 类型的对象不是 JSON 可序列化的


当我在 postman api 中运行时,我得到了上面的错误,因为 sales_qty 是 decimal ,我不知道如何解析 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:Decimal 类型的对象不是 JSON 可序列化的

最佳答案

使用带有 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

关于python - 类型错误 : Object of type Decimal is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65309377/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com