python - JSON: TypeError: Decimal ('34.3' ) 不是 JSON 可序列化的

标签 python json

<分区>

我正在运行一个返回小数列表的 SQL 查询。当我尝试将其转换为 JSON 时,出现类型错误。

查询:

res = db.execute("""
SELECT CAST ((SUM(r.SalesVolume)/1000.0) AS decimal(6,1))
FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId 
INNER JOIN Calendar c
ON r.DayId = c.DayId
WHERE c.WeekCodeInYear BETWEEN 1 AND 12
AND 
c.YearId = 2014
GROUP BY c.WeekCodeInYear """)

结果列表:

[Decimal('34.3'), Decimal('50.9'), Decimal('31.5'), Decimal('23.3'), Decimal('19
.7'), Decimal('56.9'), Decimal('43.8'), Decimal('35.2'), Decimal('29.2'), Decima
l('43.7'), Decimal('42.6'), Decimal('23.4')]

代码:

for row in res:
    testlist.append (row[0])
    print testlist

list = json.dumps(testlist)

然后我得到了 Unable to serialize error 尝试在网上查找,没有太大帮助。 请注意,最终列表将作为图表的输入数据。

最佳答案

使用覆盖默认:

import json
from decimal import Decimal

def default(obj):
    if isinstance(obj, Decimal):
        return str(obj)
    raise TypeError("Object of type '%s' is not JSON serializable" % type(obj).__name__)

json.dumps(testlist, default=default)

或者只是对 Decimal 对象执行 str:

for row in res:
    testlist.append (str(row[0]))
json.dumps(testlist)

关于python - JSON: TypeError: Decimal ('34.3' ) 不是 JSON 可序列化的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31202956/

相关文章:

iphone - iPhone 上什么速度更快? XML pList 还是 JSON?

javascript - 使用 Nodejs 进行异步编程 - 遍历链接数组,打开它们并在完成后将它们保存到 JSON

python - 在没有图形界面的集群上使用Python和opencv(ImportError : libXdmcp. so.6)

python - 如何从字符串列表创建多个变量?

javascript - Json 对象到 Div Html

objective-c - 在 Xcode 中使用 NSURLConnection 发送 JSON 数据

html - Angular JS 过滤器基于类别数组的概述

python - 如何为使用日期时间的导入函数设置时间?

python - Google API quickstart.py 错误 KeyError : '_module'

python - Flask-WTF CSRF token 丢失