Python求助:用文本文件条目匹配JSON的appid值失败,循环异常
问题:用文本文件条目匹配JSON中的对应值
需求
读取文本文件中的每行条目,匹配JSON文件里的appid值,返回所有匹配的JSON条目。
文本文件内容(apps_to_upgrade.txt)
thing1 thing2 thing3
JSON示例(dump.json)
{ "ssb": [ { "uid": 27, "appid": "thing1", "title": "Title of thing", "created_time": "2009-11-17T01:32:28+00:00", "published_time": "2009-11-17T01:32:28+00:00", "updated_time": "2022-11-14T17:26:23+00:00" } ] }
当前尝试的Python代码
import json upgrade_apps = open("apps_to_upgrade.txt", "r") ua = upgrade_apps.readlines() upgrade_apps.close() ua3 = "thing1" # 测试输出 print(ua) print(type(ua)) for atu in ua: print(atu) # ↑ 这里能输出文件里的文本 with open('dump.json') as f: data = json.load(f) f.close() jsonResult = data['ssb'] for i in jsonResult: if i['appid'] == ua3: # 这里用ua3或"thing1"能正常匹配,用atu就不行 print(i['uid'],i['appid']) break
遇到的问题
- 使用固定字符串
ua3或"thing1"可以正常匹配,但用从文件读取的atu变量无法匹配; - 尝试嵌套循环后,仅返回文本文件最后一个条目的匹配结果。
解决方法
问题根源
readlines()方法会保留每行末尾的换行符\n,导致atu的值是"thing1\n"这类带换行的字符串,和JSON里的appid(纯字符串"thing1")不相等,所以匹配失败。
修改后的代码
import json # 读取文件时去掉每行的空白字符(包括换行符) with open("apps_to_upgrade.txt", "r") as upgrade_apps: # 用strip()处理每行,同时过滤空行 ua = [line.strip() for line in upgrade_apps if line.strip()] with open('dump.json') as f: data = json.load(f) json_result = data['ssb'] # 嵌套循环:遍历每个要匹配的appid,再遍历JSON条目 for target_appid in ua: for item in json_result: if item['appid'] == target_appid: print(item['uid'], item['appid']) # 找到当前target_appid的匹配项后,跳出内层循环,继续下一个target_appid break else: # 如果内层循环没找到匹配项,执行这里 print(f"未找到匹配的appid: {target_appid}")
关键修改点
- 处理换行符:用列表推导式+
strip()处理每行,去掉换行符和前后空白,确保和JSON中的appid格式一致; - 正确的嵌套循环:遍历每个目标appid,再遍历JSON条目,找到匹配项后跳出内层循环,避免只返回最后一个结果;
- 使用上下文管理器:用
with open()自动关闭文件,更简洁安全。
内容的提问来源于stack exchange,提问作者myCodeIsJanky
相关产品推荐
相关产品推荐

