如何用Python统计两个JSON数据中ID匹配的区块数量
问题分析
你的原代码存在以下几个导致统计结果错误的问题:
- 时间线数据(timelinedata)的获取逻辑有缺陷:连续两个try语句如果都执行失败,timelinedata变量未定义会直接报错;第一个try执行成功后没有跳出逻辑,第二个try如果执行失败会覆盖掉第一个try的正确赋值。
- ID匹配规则错误:
if i in sections['sectionId']是判断timeline中的ID为sectionId的子串,你需要的是完全相等的精确匹配。 - 去重规则不合理:按区块展示名(sectionDisplayName)去重,会出现不同ID的区块重名时被误去重的问题,应该按唯一ID去重。
- 没有做最终的数量统计输出,只打印了区块名称。
修正后的代码
import requests #--------FORTNITEDATA--------# response = requests.get("https://fortnitecontent-website-prod07.ol.epicgames.com/content/api/pages/fortnite-game/shop-sections?lang=it") data = response.json()["sectionList"]['sections'] matched_sections = [] #--------ENDFORTNITEDATA--------# #--------TIMELINE--------# timelinedata = {} timeline = requests.get("https://api.nitestats.com/v1/epic/modes") timeline_json = timeline.json() states = timeline_json['channels']['client-events']['states'] # 按索引倒序找存在sectionStoreEnds的状态 for state in reversed(states): if 'sectionStoreEnds' in state.get('state', {}): timelinedata = state['state']['sectionStoreEnds'] break # 提前把所有待匹配的ID转成集合,提升查询效率 timeline_id_set = set(timelinedata.keys()) #--------ENDTIMELINE--------# def count_matched_sections(): count = 0 for section in data: section_id = section.get('sectionId') # 精确匹配ID,且同一个ID只统计一次 if section_id in timeline_id_set and section_id not in matched_sections: matched_sections.append(section_id) count +=1 display_name = section.get("sectionDisplayName", "未命名区块") print(f'{display_name}\n') return count if __name__ == "__main__": print("SEZIONI DEL NEGOZIO\n") total = count_matched_sections() print(f"匹配的区块总数:{total}")
改动说明
- 优化了timelinedata的获取逻辑:倒序遍历states数组,优先取索引大的状态,只要找到存在sectionStoreEnds的节点就停止查找,避免异常覆盖问题,同时提前初始化变量避免未定义报错。
- 把timeline中的ID提前转成集合,查询效率比嵌套循环高,也避免重复遍历。
- 改为按sectionId精确匹配,用sectionId去重,避免重名导致的统计错误。
- 新增了匹配总数返回和打印。
内容的提问来源于stack exchange,提问作者xTsubasaN122x
相关产品推荐
相关产品推荐

