JSON:TypeError:Decimal('34 .3')不可序列化JSON [英] JSON: TypeError: Decimal('34.3') is not JSON serializable
问题描述
我正在运行一个SQL查询,该查询返回一个十进制列表.当我尝试将其转换为JSON时,出现类型错误.
I am running an SQL query which returns a list of Decimals. When I try to convert this into JSON i get the type error.
查询:
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
尝试在线查找,没有太大帮助.
请注意,最终列表将作为输入数据进入图表.
And the I get the Unable to serialize error
Tried looking up online, no much help.
Please note that the final list would go as input data to a chart.
推荐答案
如错误所示,Decimal
类型不能直接序列化为JSON.如果希望将Decimal
转换为float
,可以考虑将其转换为float
,但是可能会舍入错误.即
As the error says, the Decimal
type is not able to be serialized directly into JSON. Considering casting the Decimal
into a float
if you wish to keep that as a number, however you may get rounding errors. i.e.
for row in res:
testlist.append(float(row[0]))
或者使用列表理解来构建列表,这一次我转换为str
.
Or alternatively build the list using list comprehension, this time I cast to str
.
testlist = [str(row[0]) for row in res]
后者是适当的表示形式,因为Decimal
类型可以由str
明确表示.您可以像这样抓住原始值
The latter is an appropriate representation as the Decimal
type can be unambiguously represented by str
. You can grab the original value like so
from decimal import Decimal
jlist = json.dumps(testlist) # don't use list as it's predefined type
new_list = json.loads(jlist)
new_dlist = [Decimal(s) for s in new_list]
new_dlist
应该与原始的templist
相同.
这篇关于JSON:TypeError:Decimal('34 .3')不可序列化JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!