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

Python中如何将数据库行列表转为JSON(适配多列并使用列名)

解决方案

要适配多列数据并使用数据库列名作为JSON的键,你需要让方法接收列名列表作为参数,将每一行数据与对应列名一一映射。修改后的代码如下:

import json

class JSONFormatter:
    @staticmethod
    def convert(data: list[list], column_names: list[str]) -> str:
        # 检查列名数量与每行字段数量是否匹配
        if data and len(column_names) != len(data[0]):
            raise ValueError("列名数量与每行数据的字段数量不匹配")
        
        # 将每行数据与列名映射为字典,组成列表
        result = [dict(zip(column_names, row)) for row in data]
        # 转换为格式化后的JSON字符串
        return json.dumps(result, indent=4, ensure_ascii=False)

代码说明

  • 新增column_names参数:传入数据库查询得到的列名列表(可从游标对象的描述信息中提取)
  • 使用dict(zip(column_names, row)):自动将每一行的字段值与对应列名配对成字典,完美适配任意列数
  • 边界检查:避免列名和字段数量不匹配导致的映射错误
  • ensure_ascii=False:支持中文等非ASCII字符的正确输出

使用示例

假设从数据库查询得到以下数据和列名:

# 模拟数据库查询结果:行列表
data_rows = [
    (1, "https://example.com", "文章A", 2024, True),
    (2, "https://test.com", "文章B", 2023, False)
]
# 对应数据库列名
column_names = ["id", "url", "title", "year", "is_published"]

# 转换为JSON
json_str = JSONFormatter.convert(data_rows, column_names)
print(json_str)

输出的JSON结构如下:

[
    {
        "id": 1,
        "url": "https://example.com",
        "title": "文章A",
        "year": 2024,
        "is_published": true
    },
    {
        "id": 2,
        "url": "https://test.com",
        "title": "文章B",
        "year": 2023,
        "is_published": false
    }
]

如何获取数据库列名

如果使用标准DBAPI2兼容的数据库驱动(如psycopg2、mysql-connector-python),可以通过游标对象的description属性提取列名:

import psycopg2

conn = psycopg2.connect("your_connection_string")
cursor = conn.cursor()
cursor.execute("SELECT id, url, title FROM articles")
# 提取列名
column_names = [desc[0] for desc in cursor.description]
# 获取所有数据行
data_rows = cursor.fetchall()

# 转换为JSON
json_str = JSONFormatter.convert(data_rows, column_names)

内容的提问来源于stack exchange,提问作者Musa Yılmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:45