You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何将SQL查询结果转为带列名的JSON格式返回?

问题解决:FastAPI + pyodbc 返回带列名的JSON结果

报错原因

原代码中cursor.fetchall()返回的是元组列表,jsonable_encoder无法将这种结构直接序列化为包含列名的JSON对象,因此抛出类型错误。


解决方案1:利用Pandas快速实现(已导入库,更简洁)

直接用Pandas读取数据库查询结果,自动映射列名并转换为字典列表返回:

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
import pyodbc
import pandas as pd
from fastapi import FastAPI

app = FastAPI()  # 补充原代码遗漏的FastAPI实例化

@app.get("/periodikes/sql_2")
def results_to_json():
    conn = pyodbc.connect('blah blah')
    query = "select top 100 * from table"
    
    # Pandas读取查询结果,自动关联列名
    df = pd.read_sql(query, conn)
    # 转换为字典列表,每条记录对应一个带列名的JSON对象
    result = df.to_dict(orient='records')
    
    conn.close()
    return JSONResponse(content=jsonable_encoder(result))

解决方案2:手动映射列名与数据(无需Pandas,轻量)

通过cursor.description提取列名,将每个元组数据与列名配对成字典:

from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
import pyodbc
from fastapi import FastAPI

app = FastAPI()

@app.get("/periodikes/sql_2")
def results_to_json():
    conn = pyodbc.connect('blah blah')
    cursor = conn.cursor()
    query = "select top 100 * from table"
    cursor.execute(query)
    
    # 从cursor.description中提取所有列名
    column_names = [desc[0] for desc in cursor.description]
    # 将每行元组数据与列名绑定,生成字典列表
    result = [dict(zip(column_names, row)) for row in cursor.fetchall()]
    
    cursor.close()
    conn.close()
    return JSONResponse(content=jsonable_encoder(result))

说明

两种方案最终都会返回符合需求的JSON格式:以列表形式包含多条记录,每条记录是一个键为列名、值为对应字段内容的对象。

内容的提问来源于stack exchange,提问作者asdaswsad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:01:08