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

Pandas DataFrame转JSON时如何添加外层自定义对象名transactionLines

解决方案

你只需要在原有分组逻辑处理完成后,先将结果转换为Python字典列表,再用自定义键包裹后转JSON即可,无需手动拼接字符串避免转义错误。

代码实现

import json

# 原有分组处理逻辑,先保留为DataFrame不直接转JSON
processed_df = (df_import.groupby(['Item', 'Subinventory', 'TransactionUnitOfMeasure', 'TransactionType', 'TransactionDate', 'TransactionSourceId', 'OrganizationName'])
    .apply(lambda x: x[['LotNumber', 'TransactionQuantity']].to_dict('records'))
    .reset_index()
    .rename(columns={0: 'lotItemLots'}))

# 外层添加自定义键后转JSON
output_json = json.dumps(
    {"transactionLines": processed_df.to_dict(orient='records')},
    ensure_ascii=False,  # 避免中文乱码
    indent=2  # 输出格式化缩进,和你期望的展示结构一致
)

如果不想引入json库,也可以用pandas原生方法实现:

output_json = (pd.Series([processed_df.to_dict(orient='records')], index=['transactionLines'])
               .to_json(force_ascii=False, indent=2))

两种方式输出的结构完全符合你要求的嵌套格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:51:02