下面的Python代码,可以转换任意JSON为Excel文件,convert.py:
import argparse
import pandas as pd
import json
def json_to_rows(data, parent_key=''):
"""
递归展开 JSON 数据,将嵌套的数组和对象转换为多行。
:param data: 输入的 JSON 数据
:param parent_key: 父级键路径,用于命名嵌套字段
:return: 一个列表,每个元素是一个平铺展开的行(字典格式)
"""
rows = []
if isinstance(data, dict):
base_row = {}
for key, value in data.items():
full_key = f"{parent_key}.{key}" if parent_key else key
if isinstance(value, list):
for item in value:
sub_rows = json_to_rows(item, full_key)
for sub_row in sub_rows:
rows.append({**base_row, **sub_row})
elif isinstance(value, dict):
sub_rows = json_to_rows(value, full_key)
for sub_row in sub_rows:
rows.append({**base_row, **sub_row})
else:
base_row[full_key] = value
if not rows:
rows.append(base_row)
elif isinstance(data, list):
for item in data:
rows.extend(json_to_rows(item, parent_key))
else:
rows.append({parent_key: data})
return rows
parser = argparse.ArgumentParser(description="将 JSON 数据转换为 Excel 文件")
parser.add_argument('input', nargs='?', default='data.json', help="输入的 JSON 文件名(默认:data.json)")
parser.add_argument('output', nargs='?', default='output.xlsx', help="输出的 Excel 文件名(默认:output.xlsx)")
args = parser.parse_args()
with open(args.input, 'r') as file:
data = json.load(file)
rows = json_to_rows(data)
df = pd.DataFrame(rows)
df.to_excel(args.output, index=False)
print(f"JSON 文件 {args.input} 已成功转换为 Excel 文件:{args.output}")
示例 data.json:
[
{
"label": "abc",
"positive": 0,
"value": 123,
"subs": [
{
"label": "def",
"positive": 0,
"value": 63,
"Child": [
{
"a": 1,
"b": 2,
"c_sub": [
{ "x": "x", "y": "y" },
{ "x": "m", "y": "n" }
]
},
{
"a": 3,
"b": 4
}
]
},
{
"label": "xyz",
"positive": 0,
"value": 60
}
]
},
{
"label": "AC",
"positive": 3,
"AAA": "aaa",
"value": 123,
"subs": [
{
"label": "BB",
"positive": 0,
"value": 123
},
{
"label": "BH",
"positive": 0,
"value": 123
}
]
},
{
"label": "KK",
"positive": 2,
"value": 123,
"subs": [
{
"label": "CMCC",
"positive": 0,
"value": 123
}
]
}
]
转换后的效果:
label |
positive |
value |
subs.label |
subs.positive |
subs.value |
subs.Child.a |
subs.Child.b |
subs.Child.c_sub.x |
subs.Child.c_sub.y |
AAA |
abc |
0 |
123 |
def |
0 |
63 |
1 |
2 |
x |
y |
|
abc |
0 |
123 |
def |
0 |
63 |
1 |
2 |
m |
n |
|
abc |
0 |
123 |
def |
0 |
63 |
3 |
4 |
|
|
|
abc |
0 |
123 |
xyz |
0 |
60 |
|
|
|
|
|
AC |
3 |
123 |
BB |
0 |
123 |
|
|
|
|
aaa |
AC |
3 |
123 |
BH |
0 |
123 |
|
|
|
|
aaa |
KK |
2 |
123 |
CMCC |
0 |
123 |
|
|
|
|
|