请求JSON数据触发TypeError:列表索引需为整数/切片而非字符串
解决TypeError: list indices must be integers or slices, not str问题
错误原因分析
数组索引方式错误
报错行comparename = compareblog.json()["data"]["fortnite"]["posts"]["title"]中,posts是数组类型,你直接用字符串索引["title"]访问数组——但数组仅支持整数索引或切片,这是触发TypeError的核心原因。无效的数据转换操作
yesyes = [int(blog.json())]是完全错误的写法:blog.json()返回的是字典对象,无法直接转换为整数,这行代码会导致后续所有索引操作失效,甚至引发额外的类型错误。
修复后的完整代码
import requests import time # 假设api是已初始化的推文API对象 def blog_check(): # 获取初始博客数据,正确处理posts数组 compareblog = requests.get("https://fn-api.com/api/blogposts") compare_data = compareblog.json() # 取posts数组的第一个帖子(若需监控所有帖子可改为遍历) comparename = compare_data["data"]["fortnite"]["posts"][0]["title"] count = 1 initialcheckdelay = 3 checkdelayafter = 60 while True: print(f'Waiting for blog changes -> [Count: {count}]\n') # 获取当前博客数据 blog = requests.get("https://fn-api.com/api/blogposts") current_data = blog.json() current_title = current_data["data"]["fortnite"]["posts"][0]["title"] current_desc = current_data["data"]["fortnite"]["posts"][0]["description"] current_author = current_data["data"]["fortnite"]["posts"][0]["author"] current_link = current_data["data"]["fortnite"]["posts"][0]["url"] time.sleep(initialcheckdelay) count += 1 # 检测到博客更新 if comparename != current_title: print(f"Blog change detected!") # 发布推文 api.update_status(f"New Blog Post has been detected by {current_author}!\n\n{current_title}\n{current_desc}\nLink: {current_link}") # 更新对比值,避免重复推送 comparename = current_title # 延迟后继续监控 time.sleep(checkdelayafter) blog_check()
关键修复点
- 正确处理数组索引:对
posts数组先使用整数索引(如[0])获取具体帖子对象,再访问对象内的title、description等字符串字段。 - 移除错误转换:直接使用
blog.json()返回的字典对象,不要做无意义的int转换和列表包装。 - 修复死循环问题:原代码中
while 2:会无限重复发推文,改为更新对比标题后继续外层监控循环,避免重复推送。 - 补充必要模块导入:确保导入
requests和time模块,否则会引发NameError。
内容的提问来源于stack exchange,提问作者Monks
相关产品推荐
相关产品推荐

