JSON实例如下:
{"name": "Alice", "age": 25, "city": "New York"}
{"name": "Bob", "age": 30, "city": "Los Angeles"}
{"name": "Charlie", "age": 35, "city": "Chicago"}
步骤如下:
1. 逐行读取 JSON 文件:
使用 json 模块逐行解析 JSON 数据。
2. 提取指定字段:
从每行 JSON 数据中提取需要的字段值。
3. 写入到 Excel:
使用 pandas 库将提取的数据保存到 Excel 文件。
import json
import pandas as pd
# 定义文件路径
json_file = "/filepath/data.json"
excel_file = "/filepath/output.xlsx"
# 初始化空列表,用于存储提取的数据
data_list = []
# 打开 JSON 文件逐行读取
with open(json_file, "r") as file:
for line in file:
# 解析每行 JSON 数据
data = json.loads(line.strip())
# 提取指定字段
name = data.get("name")
age = data.get("age")
city = data.get("city")
# 将提取的字段添加到列表
data_list.append({"Name": name, "Age": age, "City": city})
# 将列表转换为 Pandas DataFrame
df = pd.DataFrame(data_list)
# 将 DataFrame 写入到 Excel 文件
df.to_excel(excel_file, index=False, engine="openpyxl")
print(f"数据已成功保存到 {excel_file}")
注1:如果JSON格式不严谨,例如包含过多的换行符,空格等,导致按行读取解析报错,我们还需要再将JSON数据转为Excel之前,首先将JSON格式转换为紧凑格式,也就是我们前面提高的样例数据格式。
with open(json_file, "r", encoding="utf-8") as file:
data = json.load(file)
compact_json = json.dumps(data, separators=(",", ":"))
with open(output_file, "w", encoding="utf-8") as file:
file.write(compact_json)
注2:如果 JSON 中存在嵌套结构,可以使用键路径提取字段。
样例数据如下:
{"name": "Alice", "details": {"age": 25, "city": "New York"}}
{"name": "Bob", "details": {"age": 30, "city": "Los Angeles"}}
with open(json_file, "r") as file:
for line in file:
data = json.loads(line.strip())
# 提取嵌套字段
name = data.get("name")
age = data.get("details", {}).get("age")
city = data.get("details", {}).get("city")
data_list.append({"Name": name, "Age": age, "City": city})
import pandas as pd
# 定义 Excel 文件路径和输出 JSON 文件路径
excel_file = "data.xlsx"
json_file = "output.json"
# 读取 Excel 文件到 Pandas DataFrame
df = pd.read_excel(excel_file)
# 将 DataFrame 转换为 JSON 格式并保存到文件
df.to_json(json_file, orient="records", force_ascii=False, indent=4)
print(f"数据已成功保存到 {json_file}")
代码说明
1. pd.read_excel():
• 读取 Excel 文件并将其加载到 Pandas 的 DataFrame 中。
• 默认读取第一个工作表,如果需要指定工作表,可以添加参数 sheet_name="Sheet1"。
2. df.to_json():
• 将 DataFrame 转为 JSON 格式。
常用参数
• orient="records": 每一行作为一个 JSON 对象。
• force_ascii=False: 保留非 ASCII 字符(如中文)。
• indent=4: 使 JSON 格式化易读。
JSON 文件输出
• 转换后的 JSON 数据直接保存到文件中。
样例Excel数据如下:
Name | Age | City |
---|---|---|
Alice | 25 | New York |
Bob | 30 | Los Angeles |
Charlie | 35 | Chicago |
样例数据输出JSON数据如下:
[
{
"Name": "Alice",
"Age": 25,
"City": "New York"
},
{
"Name": "Bob",
"Age": 30,
"City": "Los Angeles"
},
{
"Name": "Charlie",
"Age": 35,
"City": "Chicago"
}
]
# 读取 Excel 文件中的所有工作表
excel_data = pd.read_excel(excel_file, sheet_name=None) # 返回一个字典,键是工作表名
# 遍历每个工作表并保存为单独的 JSON 文件
for sheet_name, data in excel_data.items():
json_file = f"{sheet_name}.json"
data.to_json(json_file, orient="records", force_ascii=False, indent=4)
print(f"工作表 {sheet_name} 数据已保存到 {json_file}")
依赖库
pip install openpyxl
pip install pandas
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。