如何在Python中将API返回的嵌套JSON转换为指定格式CSV?
如何将嵌套JSON转换为指定格式的CSV
针对你这种固定结构的嵌套JSON(每个条目包含team和coach两个子字典),可以用脚本直接合并子字典后写入CSV,以下是两种常用编程语言的实现方案:
Python 实现
Python的csv模块可以轻松处理这种需求,步骤简单直接:
import csv # 假设这是你从API获取到的数据列表 api_data = [ { "team": { "division": "divison1", "rank": 1, "team_name": "team name 1", "team_id": "82f9a58f", "value": 1450, "score": 2417, "w/d/l": "35/10/6" }, "coach": { "coach_name": "coach a", "coach_id": "4364b994", "lang": "english", "country": None } } ] # 合并每个条目的team和coach子字典,得到单层结构 flattened_data = [{**item['team'], **item['coach']} for item in api_data] # 严格按照你需要的列顺序定义表头 target_headers = ["division", "rank", "team_name", "team_id", "value", "score", "w/d/l", "coach_name", "coach_id", "lang", "country"] # 写入CSV文件 with open('team_coach_data.csv', 'w', newline='', encoding='utf-8') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=target_headers) writer.writeheader() # 写入表头 writer.writerows(flattened_data) # 写入所有数据行
关键说明
- 用
{**item['team'], **item['coach']}快速合并两个子字典,直接得到符合CSV要求的单层结构 csv.DictWriter会严格按照你指定的target_headers顺序写入列,确保和目标格式一致- Python中的
None会自动被转换为CSV中的null,完全匹配需求
JavaScript(Node.js)实现
如果你的脚本是基于Node.js编写的,可以用以下代码:
const fs = require('fs'); // API返回的嵌套数据 const apiData = [ { "team": { "division": "divison1", "rank": 1, "team_name": "team name 1", "team_id": "82f9a58f", "value": 1450, "score": 2417, "w/d/l": "35/10/6" }, "coach": { "coach_name": "coach a", "coach_id": "4364b994", "lang": "english", "country": null } } ]; // 合并子字典 const flattenedData = apiData.map(item => ({...item.team, ...item.coach})); // 指定目标表头顺序 const targetHeaders = ["division", "rank", "team_name", "team_id", "value", "score", "w/d/l", "coach_name", "coach_id", "lang", "country"]; // 生成CSV内容 const csvRows = [ targetHeaders.join(','), ...flattenedData.map(row => targetHeaders.map(field => { const value = row[field]; // 处理特殊情况:null值转字符串,包含引号的字段转义 return value === null ? 'null' : `"${String(value).replace(/"/g, '""')}"`; }).join(',')) ]; const csvContent = csvRows.join('\n'); // 写入文件 fs.writeFileSync('team_coach_data.csv', csvContent, 'utf8');
内容的提问来源于stack exchange,提问作者Trevor Turn
相关产品推荐
相关产品推荐

