You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Excel/CSV行数据值映射到现有JSON模板?

实现Excel行数据到指定JSON模板的映射

准备工作

  • 安装依赖库:执行 pip install pandas 用于读取Excel文件
  • 梳理好Excel列名与JSON模板字段的对应关系,比如Excel的「姓名」对应模板里的user_info.name,「邮箱」对应user_info.contact.email

具体实现代码

1. 读取Excel数据

先把Excel里的每行数据转成字典格式,方便后续映射:

import pandas as pd

# 读取Excel文件,假设表头在第一行
df = pd.read_excel("你的数据文件.xlsx")
# 将每行数据转为字典,生成字典列表
excel_rows = df.to_dict("records")

2. 定义JSON模板

把你的JSON模板写成Python字典(注意保持和目标JSON结构一致):

# 示例模板,根据你的实际模板修改
json_template = {
    "user_info": {
        "name": "",
        "age": 0,
        "contact": {
            "email": "",
            "phone": ""
        }
    },
    "metadata": {
        "source": "Excel导入",
        "create_time": ""
    }
}

3. 编写映射逻辑

遍历每行Excel数据,将对应值填充到模板中,处理嵌套字段:

import json
from datetime import datetime

def fill_template(row):
    # 复制模板,避免修改原模板对象
    filled_template = json_template.copy()
    # 浅拷贝嵌套字典,否则会修改原模板的嵌套部分
    filled_template["user_info"] = filled_template["user_info"].copy()
    filled_template["user_info"]["contact"] = filled_template["user_info"]["contact"].copy()
    
    # 按对应关系填充值
    filled_template["user_info"]["name"] = row["姓名"]
    filled_template["user_info"]["age"] = row["年龄"]
    filled_template["user_info"]["contact"]["email"] = row["邮箱"]
    filled_template["user_info"]["contact"]["phone"] = row["电话"]
    
    # 动态生成字段示例:填充当前时间
    filled_template["metadata"]["create_time"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    return filled_template

# 批量处理所有行
final_json_data = [fill_template(row) for row in excel_rows]

4. 保存结果

将生成的JSON数据写入文件:

# 保存为格式化的JSON文件,支持中文
with open("输出结果.json", "w", encoding="utf-8") as f:
    json.dump(final_json_data, f, ensure_ascii=False, indent=4)

关键注意点

  • 处理空值:如果Excel存在缺失数据,用row.get("列名", "默认值")替代直接取值,避免KeyError
  • 类型匹配:确保Excel数据类型和模板字段一致,比如数字类型不要存成字符串,日期统一转成指定格式的字符串
  • 嵌套字段拷贝:模板里的嵌套字典要单独拷贝,否则会出现所有行共享同一嵌套对象的问题

内容的提问来源于stack exchange,提问作者Rohit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 03:37:01