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

如何使用Python将CSV特定列数据拆分为嵌套JSON数据结构?

解决CSV转指定嵌套JSON结构的问题

需求目标

需要将CSV数据转换为如下嵌套结构的JSON:

{
    "name": "Place",
    "Details": [
      {
        "detail": "I",
        "info": [
          "Iran",
          "Iraq"
        ]
      },
      {
        "detail": "J",
        "info": "Japan"
      }
    ]
  }

现有问题

使用pd.to_json(orient="records")只能生成扁平化的记录数组,无法实现info字段的多值拆分转数组,也无法构建外层的name和Details嵌套结构。

解决方案

假设你的CSV结构为两列(detail和info,其中info列可能包含逗号分隔的多个值):

detailinfo
IIran,Iraq
JJapan

可以通过以下代码实现需求:

import pandas as pd
import json

# 读取CSV数据
path = "/content/file.csv"
df = pd.read_csv(path)

# 处理info列:逗号分隔值转数组,单个值保留字符串格式
def parse_info(info_str):
    items = [item.strip() for item in info_str.split(",")]
    return items if len(items) > 1 else items[0]

df["info"] = df["info"].apply(parse_info)

# 构建目标嵌套结构
final_result = {
    "name": "Place",
    "Details": df.to_dict("records")
}

# 输出格式化后的JSON
print(json.dumps(final_result, indent=2))

代码说明

  • parse_info函数:按逗号拆分info列字符串,去除首尾空格后,根据元素数量决定返回列表或单个字符串,匹配目标JSON的格式要求。
  • 手动构建外层结构:直接通过字典定义name和Details字段,Details的值由DataFrame转换为记录字典数组得到。
  • 使用json.dumps格式化输出,保证JSON结构的可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:50:28