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

使用Python Pandas将CSV转JSON时的格式问题求助

解决CSV转指定结构JSON的格式问题

原代码使用orient='records'会生成数组型JSON,每个元素对应CSV的一行,但目标是键值对型JSON(以稀有度标识为键,属性为值),需要调整处理逻辑:

核心解决方案代码

import pandas as pd
import json

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

# 将CSV中作为目标JSON键的列设为索引(例如'id'列,根据实际CSV结构调整)
df.set_index('id', inplace=True)

# 转换为嵌套字典结构(匹配目标JSON的键值对格式)
result = df.to_dict('index')

# 写入JSON文件,带格式化缩进
with open('rarities.json', 'w', encoding='utf-8') as f:
    json.dump(result, f, indent=2, ensure_ascii=False)

关键调整说明

  1. 索引设置:通过set_index指定目标JSON的键对应的CSV列(比如CSV中的id字段),确保输出的JSON以该字段值为键。
  2. 字典转换:使用to_dict('index')将DataFrame转换为{索引值: {列名: 值}}的结构,完全匹配目标JSON的键值对格式。
  3. 格式化输出:用json.dump的indent参数生成可读性更强的格式化JSON,ensure_ascii=False避免中文乱码(如果有)。

处理嵌套结构(若目标JSON有嵌套属性)

如果目标JSON包含嵌套对象(比如upgradeCost下的多级属性),而CSV列名用.分隔层级(如upgradeCost.1),可额外处理列名生成嵌套结构:

import pandas as pd
import json

df = pd.read_csv('rarities.csv')
df.set_index('id', inplace=True)

# 将带分隔符的列名拆分为多级索引,自动生成嵌套结构
df.columns = pd.MultiIndex.from_tuples([tuple(col.split('.')) for col in df.columns])
result = df.to_dict('index')

with open('rarities.json', 'w', encoding='utf-8') as f:
    json.dump(result, f, indent=2, ensure_ascii=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:55:44