如何自动从Excel提取数据生成同结构多份JSON负载?
解决方案:从Excel批量生成参数化JSON负载
依赖安装
首先安装处理Excel和JSON所需的Python库:
pip install pandas openpyxl
实现代码
假设你的Excel文件列名与JSON参数名完全匹配(advertiserIdType、advertiserId、process等),以下是可直接复用的代码:
import pandas as pd import json # 1. 读取Excel数据 # 替换为你的Excel文件路径 df = pd.read_excel("advertiser_data.xlsx", engine="openpyxl") # 2. 定义固定的JSON模板 # 根据你的实际负载结构修改模板内容 json_template = { "advertiserInfo": { "advertiserIdType": "", "advertiserId": "" }, "process": "", # 其他固定字段直接保留原值 "requestType": "ADVERTISER_SYNC", "timestamp": 1699999999 } # 3. 批量生成JSON for idx, row in df.iterrows(): # 复制模板避免修改原结构 target_json = json_template.copy() # 替换对应参数 target_json["advertiserInfo"]["advertiserIdType"] = row["advertiserIdType"] target_json["advertiserInfo"]["advertiserId"] = str(row["advertiserId"]) # 强制转字符串避免数字格式问题 target_json["process"] = row["process"] # 输出为单个JSON文件(文件名按序号区分) with open(f"advertiser_payload_{idx+1}.json", "w", encoding="utf-8") as f: json.dump(target_json, f, indent=4, ensure_ascii=False) # 可选:将所有JSON追加到一个批量文件(每行一个JSON对象) # with open("all_payloads.json", "a", encoding="utf-8") as f: # json.dump(target_json, f, ensure_ascii=False) # f.write("\n")
关键注意事项
- 确保Excel列名与代码中引用的列名完全一致,大小写敏感
- 如果JSON模板有嵌套结构,要对应好层级路径(比如示例中的
advertiserInfo下的子字段) - 对于ID类字段,建议用
str()强制转换为字符串,避免Excel中数字类型导致JSON输出出现不必要的格式问题 - 输出方式可根据需求选择:单文件输出便于单独使用,批量文件适合后续批量处理
内容的提问来源于stack exchange,提问作者Soham Sinha
相关产品推荐
相关产品推荐

