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

2izufjch  于 2023-08-08  发布在  其他
关注(0)|答案(3)|浏览(121)

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

1tu0hz3e

1tu0hz3e1#

使用json.dump和cls参数,我相信当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

字符串

lvjbypge

lvjbypge2#

import decimal

from flask import current_app as app
from flask import Jsonify
from flask.json import JSONEncoder

class JsonEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            return float(obj)
        return JSONEncoder.default(self, obj)

@app.route('/test_jsonify')
def test_jsonify():
    data = {
        'float': 7.5,
        'decimal': decimal.Decimal(7.5)
    }

    app.json_encoder = JsonEncoder
    return jsonify(data)

字符串
(在这里找到Flask Jsonify Custom JsonEncoder | Lua Software Code

fnvucqvd

fnvucqvd3#

您可以将json.dumps()与默认编码器str()一起使用。

json.dumps( dict_obj_with_decimal , default = str)

字符串

相关问题