我正在嘗試將 pyodbc 查詢的結果發送到我的視圖,但我得到了一個TypeError: Object of type Row is not JSON serializable.
假設我在 SQL Server 中有這樣的表:
| col1 | col2 | col3 |
|---|---|---|
| 1 | val1 | val2 |
| 2 | val3 | val4 |
我通過 pyodbc 查詢它并將資料傳遞給視圖,如下所示:
return render_template(
'index.html'
,data={
'foor':'bar'
,'rows':db.execute(
'SELECT * '
'FROM [' table.schema_name '].[' table.table_name ']'
).fetchall()
}
)
如果我列印{{ data.rows }}我想擁有[[1,"val1","val2"],[2,"val3","val4"]]但我得到[(Decimal('1'), 'val1', 'val2'), (Decimal('2'), 'val3', 'val4')].
如果我print(type(data.rows))在控制器中,我會獲得<class 'list'>.
嘗試在視圖中將其轉換為 JSON,{{ data.rows|tojson }}結果為TypeError: Object of type Row is not JSON serializable. 如何滿足我的需求?
uj5u.com熱心網友回復:
fetchall()回傳pyodbc.Row物件串列。行物件類似于元組,但正如錯誤訊息所述,它們不是 JSON 可序列化的。
results = crsr.execute(query).fetchall()
print(f"{type(results)} of type {type(results[0])}")
# <class 'list'> of type <class 'pyodbc.Row'>
json_string = json.dumps(results)
# TypeError: Object of type Row is not JSON serializable
我們可以將 Row 物件轉換為真正的元組,以便它們可以被序列化:
results = [tuple(row) for row in results]
print(f"{type(results)} of type {type(results[0])}")
# <class 'list'> of type <class 'tuple'>
json_string = json.dumps(results)
# no error (unless the tuples themselves contain elements that are not serializable)
如果元組確實包含不可序列化的元素(如Decimal物件),那么我們可以將它們強制為字串......
json_string = json.dumps(results, default=str)
…或者我們可以修改查詢以將小數轉換為浮點數,例如,使用
query = "SELECT CAST(x AS FLOAT) AS x FROM tbl"
代替
query = "SELECT x FROM tbl"
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/456117.html
下一篇:無法查詢和遍歷資料庫
