Python如何将多个月度API请求结果合并写入同一个JSON文件
Python多月份API数据合并存储代码修改方案
完整可运行代码
from urllib.request import urlopen import json from datetime import datetime import calendar # -------------------------- 请修改以下配置参数 -------------------------- API_BASE = "apilink/getKwh" TOKEN = "你的实际token" CLIENT_ID = "你的实际clientId" SITE_ID = "你的实际siteId" # 要拉取的起止年月,格式为(年, 月) START_YM = (2021, 1) END_YM = (2021, 12) # 存储文件路径 SAVE_PATH = "data.json" # ----------------------------------------------------------------------- all_data = [] current_year, current_month = START_YM end_year, end_month = END_YM while (current_year, current_month) <= (end_year, end_month): # 计算当月第一天和最后一天 _, last_day = calendar.monthrange(current_year, current_month) from_date = f"{current_year}-{current_month:02d}-01" to_date = f"{current_year}-{current_month:02d}-{last_day:02d}" # 拼接请求URL req_url = f"{API_BASE}?token={TOKEN}&clientId={CLIENT_ID}&siteId={SITE_ID}&from={from_date}&to={to_date}" try: # 发起请求解析数据 response = urlopen(req_url) monthly_data = json.loads(response.read()) # 合并当月数据到总列表 if "data_json" in monthly_data and len(monthly_data["data_json"]) > 0: all_data.extend(monthly_data["data_json"]) print(f"已成功拉取 {current_year}年{current_month}月 数据") except Exception as e: print(f"拉取 {current_year}年{current_month}月 数据失败,错误信息:{str(e)}") # 计算下一个月 if current_month == 12: current_year += 1 current_month = 1 else: current_month += 1 # 写入合并后的数据到JSON文件 final_output = {"data_json": all_data} with open(SAVE_PATH, "w", encoding="utf-8") as f: json.dump(final_output, f, ensure_ascii=False, indent=2) print(f"所有数据合并完成,已保存到 {SAVE_PATH},共 {len(all_data)} 条记录")
核心修改说明
- 新增了日期自动生成逻辑:通过
calendar.monthrange自动计算每个月的最后一天,不需要手动填写每个月的起止日期 - 新增了数据合并逻辑:每次请求拿到的单月数据会通过
extend方法追加到总列表中,避免覆盖之前的数据 - 修复了原代码的错误:移除了
json.dumps中无效的data2参数,避免语法报错 - 新增了异常捕获逻辑:单个月份请求失败不会中断整个拉取流程,会打印错误信息后继续拉取下一个月的数据
- 优化了文件写入方式:用
with open语法自动管理文件句柄,避免手动关闭文件可能出现的遗漏问题
自定义调整提示
- 你可以修改
START_YM和END_YM的数值,调整需要拉取的时间范围 - 如果需要保留原文件的历史数据,可以在代码开头先读取已有JSON文件的内容,追加到
all_data列表中再开始拉取新数据
内容的提问来源于stack exchange,提问作者Taariq Toffar
相关产品推荐
相关产品推荐

