这是在app.py
中运行的代码
@app.route("/", subdomain="dev")
def devhome():
with open("D:/moviewebsite/movielist.json", "r") as f:
movielist = json.load(f)
goodmovies = []
for item in movielist:
if str(item["link"])[-4:] == ".mp4":
goodmovies.append(item)
else:
return render_template("devHome.html", movielist=goodmovies)
字符串
下面是movielist.json
文件的一个片段,供参考:
{
"12 Years a Slave.mp4": {
"title": "12 Years a Slave",
"link": "12 Years a Slave.mp4",
"count": 1,
"download": "https://linknotimportant/12 Years a Slave.mp4",
"torrent": ""
}
}
型
这是我得到的错误消息:
File "d:\moviewebsite\app.py", line 70, in devhome
if str(item["link"])[-4:] == ".mp4":
TypeError: string indices must be integers
型
我试图检查是否最后4位的字符串从数组是我想要他们是正确的文件类型。
3条答案
按热度按时间dkqlctbz1#
我的答案是打开字典与项目
字符串
仅仅因为我在循环中并不意味着当for循环中的项目只是一个字符串时,我可以将项目用作数组,
所以我不得不重新打开字典
3bygqnnd2#
json.load
返回JSON文件中的顶层对象-在本例中是dict
。迭代dict
直接得到字符串(dict
的键)。将
for
循环行替换为for key, item in movielist.items():
。您的代码将变为:字符串
cfh9epnr3#
TL、DR -这是一个解决方案
字符串
说明:
'movie'是一个字典。要遍历它,你需要使用.keys()、.values()或.items()。