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

如何在Python中将DataFrame生成的JSON数组包装到transactions键中

问题描述

我用df.to_json(orient='records')从Pandas DataFrame导出了如下JSON:

[{
    "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
    "account": "21",
    "date": "2021-12-06",
    "amount": "54.4"
}, {
    "id": "508784e4-370d-450d-bed0-8f52da7469dd",
    "account": "21",
    "date": "2022-01-10",
    "amount": "20"
}]

需要转换成API要求的格式:

{
    "transactions": [{
        "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
        "account": "21",
        "date": "2021-12-06",
        "amount": "54.4"
    }, {
        "id": "508784e4-370d-450d-bed0-8f52da7469dd",
        "account": "21",
        "date": "2022-01-10",
        "amount": "20"
    }]
}

原始DataFrame数据如下:

id        date amount category account  
0  fc29706f-e041-46f6-88ff-cbab891da63c  2021-12-06   54.4    21
1  508784e4-370d-450d-bed0-8f52da7469dd  2022-01-10     20    20

请问在Python中实现该转换的最优方法是什么?

最优实现方法

直接从DataFrame生成目标格式(推荐)

跳过中间的records JSON步骤,直接将DataFrame转为字典后包装成目标结构,减少序列化/反序列化的额外开销:

import pandas as pd
import json

# 假设你的DataFrame为df
target_dict = {"transactions": df.to_dict(orient='records')}
# 转为带缩进的格式化JSON字符串
target_json = json.dumps(target_dict, indent=4)

也可以直接用Pandas的JSON工具类完成:

target_json = pd.io.json.dumps({"transactions": df.to_dict(orient='records')}, indent=4)

已有records格式JSON字符串时的转换

如果已经拿到了df.to_json(orient='records')生成的字符串,用json模块解析后重新包装即可:

import json

# 示例records格式JSON字符串
records_json = '''[{
    "id": "fc29706f-e041-46f6-88ff-cbab891da63c",
    "account": "21",
    "date": "2021-12-06",
    "amount": "54.4"
}, {
    "id": "508784e4-370d-450d-bed0-8f52da7469dd",
    "account": "21",
    "date": "2022-01-10",
    "amount": "20"
}]'''

# 解析并包装成目标结构
transactions_list = json.loads(records_json)
target_json = json.dumps({"transactions": transactions_list}, indent=4)

注意事项

  • 优先选择直接从DataFrame生成的方法,性能更优
  • 若需自定义日期格式、数值格式等,可在json.dumps中传入default参数处理,或在DataFrame导出前完成数据格式转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:45:30