悠悠楠杉
Python数据格式互转实战指南:JSON/CSV/Excel高效转换技巧
本文详解Python实现JSON/CSV/Excel三种数据格式的相互转换方法,包含5种实战场景、7个代码模板及性能优化建议,助你快速掌握数据格式转换核心技能。
一、为什么需要数据格式转换?
在数据分析、Web开发和自动化办公场景中,我们常遇到这样的困境:后端API返回JSON数据但业务部门需要Excel报表,市场调研获得CSV文件而数据库只接受JSON格式...据2023年Stack Overflow调研显示,27%的数据处理时间消耗在格式转换环节。
Python凭借其强大的生态库成为解决这类问题的利器。下面我们通过具体场景,演示如何用Python实现三大格式的自由转换。
二、JSON与CSV的相爱相杀
场景1:API数据转存为CSV
当从RESTful API获取JSON数据后,常需要转换为CSV供Excel分析:
python
import json
import csv
def jsontocsv(jsonfile, csvfile):
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f) # 加载JSON数据
if isinstance(data, list) and data:
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
print(f"转换完成,共处理{len(data)}条记录")
else:
print("数据格式异常,请检查JSON结构")
示例调用
jsontocsv('apidata.json', 'outputreport.csv')
避坑指南:
- 处理嵌套JSON时建议先用json_normalize
展平结构
- 中文乱码问题需统一使用UTF-8编码
- 大数据量建议分块处理(chunk)
场景2:CSV转JSON供前端使用
逆向转换同样常见,比如将Excel导出的CSV转为前端需要的JSON格式:
python
import pandas as pd
def csvtojson(csvfile, jsonfile, orient='records'):
df = pd.readcsv(csvfile)
df.tojson(jsonfile, force_ascii=False, orient=orient, indent=2)
print(f"转换完成,数据维度:{df.shape}")
orient参数说明:
- 'records':行记录数组(默认)
- 'index':索引字典格式
- 'columns':列字段字典格式
三、Excel的优雅处理方案
场景3:多Sheet Excel转JSON树形结构
处理包含多个工作表的Excel文件时,可构建层级化JSON:
python
from openpyxl import load_workbook
import json
def exceltojson(excelfile, jsonfile):
wb = loadworkbook(excelfile)
result = {}
for sheet in wb.sheetnames:
ws = wb[sheet]
data = []
headers = [cell.value for cell in ws[1]] # 首行为标题
for row in ws.iter_rows(min_row=2, values_only=True):
data.append(dict(zip(headers, row)))
result[sheet] = data
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"转换完成,共处理{len(wb.sheetnames)}个工作表")
性能对比:
| 库名称 | 读取速度 | 内存占用 | 功能完整性 |
|-----------|----------|----------|------------|
| openpyxl | 中等 | 较高 | ★★★★★ |
| pandas | 最快 | 最低 | ★★★★☆ |
| xlrd | 较慢 | 低 | ★★★☆☆ |
四、高级技巧与性能优化
1. 流式处理大文件
使用生成器避免内存溢出:
python
import ijson
def processlargejson(inputfile, outputfile):
with open(outputfile, 'w') as outf:
out_f.write('[')
first = True
for item in ijson.items(open(input_file, 'rb'), 'item'):
if not first:
out_f.write(',')
json.dump(item, out_f)
first = False
out_f.write(']')
2. 数据类型自动推断
解决CSV导入时的类型混乱问题:
python
def smart_convert(value):
try:
return int(value)
except ValueError:
try:
return float(value)
except ValueError:
if value.lower() in ('true', 'false'):
return value.lower() == 'true'
return value
五、完整代码模板封装
建议将常用功能封装为工具类:
python
class DataConverter:
@staticmethod
def jsontoexcel(jsondata, excelfile):
"""支持路径或文件对象输入"""
df = pd.readjson(jsondata) if isinstance(jsondata, str) \
else pd.DataFrame(jsondata)
df.toexcel(excelfile, index=False)
@staticmethod
def excel_to_json(excel_file, json_file=None, orient='records'):
df = pd.read_excel(excel_file)
return df.to_json(json_file, orient=orient) if json_file \
else df.to_dict(orient=orient.replace('records','list'))
六、总结与最佳实践
格式选择原则:
- JSON:适合嵌套数据/Web传输
- CSV:适合扁平化大数据
- Excel:适合需要多工作表展示的场景
性能优化路线:
- 小文件:直接使用pandas
- 大文件:采用流式处理
- 超大数据:考虑Dask等分布式方案
异常处理要点:
- 添加编码检测逻辑(chardet库)
- 处理日期时间等特殊格式
- 验证数据完整性(如非空检查)
最后提醒:实际业务中建议添加日志记录和单元测试,对于敏感数据转换还要考虑加密处理。完整项目示例可参考Github上的data-converter-toolkit仓库。