TypeError:类型为Decimal的对象不可JSON序列化 [英] TypeError: Object of type Decimal is not JSON serializable

查看:22
本文介绍了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序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆