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

Python实现含嵌套对象的CSV转扁平化JSON,求第三方库方案

解决方案:CSV嵌套JSON字段的扁平化处理

用第三方库 pandas 快速实现

pandas 是处理这类结构化数据转换的首选工具,能轻松解析嵌套的JSON字段并展开到顶层:

import pandas as pd
import json

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

# 解析_data列的JSON字符串为字典,展开成单独列
df = df.join(df['_data'].apply(json.loads).apply(pd.Series))

# 删除原来的_data列
df = df.drop('_data', axis=1)

# 转换为扁平化的JSON(按行输出)
flattened_json = df.to_json(orient='records', indent=2)
print(flattened_json)

运行后会输出符合你需求的扁平化JSON数组,每一行对应原CSV的一条记录。

用标准库手动实现(无需第三方依赖)

如果不想安装额外库,用Python内置的csv和json模块也能完成:

import csv
import json

flattened_records = []

with open('your_file.csv', 'r', newline='') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # 解析_data字段的JSON字符串
        nested_data = json.loads(row.pop('_data'))
        # 合并顶层字段和嵌套字段
        flattened_row = {**row, **nested_data}
        flattened_records.append(flattened_row)

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

这段代码会逐行读取CSV,解析嵌套的JSON字段后和其他字段合并,最终生成扁平化的JSON数组。

说明

两种方法都能自动处理所有行的嵌套字段,不需要手动提取前两行的键——解析JSON后会自动获取嵌套字段的键并合并到顶层,比你当前的方法更高效可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:03:21