利用python实现json转execl

要将JSON数据转换为Excel文件,可以使用Python的pandas库,它提供了高效的数据处理能力。以下是详细的实现步骤:

步骤1:安装依赖库

1
pip install pandas openpyxl
  • pandas:用于数据处理和Excel文件操作
  • openpyxl:作为Excel写入引擎(pandas依赖)

步骤2:实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import json
import pandas as pd
from pathlib import Path

def json_to_excel(input_path, output_path, sheet_name="Sheet1", encoding="utf-8"):
"""
将JSON文件转换为Excel文件

参数:
input_path: JSON文件路径(或JSON格式字符串)
output_path: 输出的Excel文件路径
sheet_name: Excel工作表名称(默认"Sheet1")
encoding: 文件编码(默认utf-8)
"""
# 检测输入类型(文件路径还是JSON字符串)
if isinstance(input_path, str) and Path(input_path).exists():
with open(input_path, 'r', encoding=encoding) as f:
data = json.load(f)
else:
data = json.loads(input_path) # 直接解析JSON字符串

# 转换数据为DataFrame
df = pd.json_normalize(data, sep="_") # 展平嵌套结构

# 写入Excel
df.to_excel(
output_path,
sheet_name=sheet_name,
index=False, # 不写入行索引
engine="openpyxl" # 指定引擎
)
print(f"成功转换: {output_path}")

# 示例用法
if __name__ == "__main__":
# 示例1:从JSON文件转换
json_to_excel(
input_path="input.json",
output_path="output.xlsx",
sheet_name="Data"
)

# 示例2:直接使用JSON字符串
json_str = '''
[
{"id": 1, "name": "Alice", "scores": {"math": 90, "english": 85}},
{"id": 2, "name": "Bob", "scores": {"math": 78, "english": 92}}
]
'''
json_to_excel(
input_path=json_str,
output_path="from_string.xlsx"
)

关键功能说明

  1. 自动展平嵌套结构
    使用pd.json_normalize()处理嵌套JSON对象(如示例中的”scores”字段),通过sep参数指定分隔符(例如scores_math)。

  2. 支持多种输入类型

    • 可直接传入JSON文件路径
    • 可直接传入JSON格式字符串
  3. 保留原始数据结构

    • 列表直接转为多行数据
    • 字典键自动转为列标题

处理前JSON示例 (input.json)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[
{
"id": 1,
"name": "Alice",
"contact": {
"email": "alice@example.com",
"phone": "123-456"
},
"hobbies": ["Reading", "Swimming"]
},
{
"id": 2,
"name": "Bob",
"contact": {
"email": "bob@example.com",
"phone": "789-012"
},
"hobbies": ["Gaming"]
}
]

生成Excel效果

id name contact_email contact_phone hobbies
1 Alice alice@example.com 123-456 [Reading, Swimming]
2 Bob bob@example.com 789-012 [Gaming]

注意事项

  1. 复杂嵌套处理
    对于多层嵌套结构(如列表套字典),可能需要预处理JSON数据或多次调用json_normalize

  2. 大数据集优化
    处理超大型JSON文件时:

    • 分块读取JSON数据
    • 使用pd.concat()合并DataFrame
    • 考虑使用xlsxwriter引擎提升性能
  3. 特殊数据类型
    Excel不支持的数据类型(如日期时间对象)建议先转换为字符串再写入。

此方案适用于大多数常见JSON结构,可通过调整json_normalize参数适应个性化需求。