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

Python中如何将CSV转换为含数组的复杂嵌套JSON

问题:将CSV按指定字段聚合为嵌套JSON

我尝试将CSV文件转换为复杂嵌套JSON格式,使用的CSV样例数据如下:

样例CSV数据

  • 字段表头:title,section_id,content,expected
  • 数据行内容:
"Test case1",1234,"Test step1","Expected Result1"
"Test case1",1234,"Test step2","Expected Result2"
"Test case1",1234,"Test step3","Expected Result3"

预期输出要求

将相同title、section_id的记录合并,把每行的content、expected字段整合为custom_steps_separated数组下的子对象,预期JSON结构如下:

[
  {
    "title": "Test case1",
    "section_id": 1234,
    "custom_steps_separated": [
      {
        "content": "Test step1",
        "expected": "Expected Result1"
      },
      {
        "content": "Test step2",
        "expected": "Expected Result2"
      },
      {
        "content": "Test step3",
        "expected": "Expected Result3"
      }
    ]
  }
]

现有问题代码

import pandas as pd
df = pd.read_csv('testcases.csv')
df['custom_steps_separated'] = df[['content','expected']].to_dict('records')
out = df[['title','section_id','custom_steps_separated']].to_json(orient='records', indent=4)
jsondict = json.loads(out)
for i in range(0,len(jsondict)):
 print(list(jsondict)[i])

上述代码未对同title、section_id的记录做聚合合并,无法生成符合要求的嵌套JSON结构。


解决方案

现有代码的核心问题是缺少分组逻辑,逐行转换会生成多条重复的用例记录,用pandas内置的groupby做分组聚合即可实现需求,修正后代码如下:

import pandas as pd
import json

# 读取CSV文件
df = pd.read_csv('testcases.csv')

# 按用例维度分组聚合
result = df.groupby(['title', 'section_id'], as_index=False).apply(
    lambda x: {
        "title": x.name[0],
        "section_id": x.name[1],
        "custom_steps_separated": x[["content", "expected"]].to_dict("records")
    }
).tolist()

# 输出格式化后的JSON到文件
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(result, f, indent=4, ensure_ascii=False)

代码说明

  • 分组键选title和section_id,确保同一个测试用例的所有步骤被归为同一组
  • 分组后每组的name属性就是对应的分组键值,直接取来作为公共字段即可,不需要额外去重
  • 组内的content和expected直接转成字典列表,赋值给custom_steps_separated字段,完全匹配预期结构
  • 如果只需要控制台打印结果,把写文件部分换成print(json.dumps(result, indent=4, ensure_ascii=False))即可
  • ensure_ascii=False参数是为了兼容中文等非ASCII字符,纯英文场景可以省略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 09:39:57