This is the code that is running in 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)
This is a snippet of the movielist.json
file for reference:
{
"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": ""
}
}
This is the error message I get:
File "d:moviewebsiteapp.py", line 70, in devhome
if str(item["link"])[-4:] == ".mp4":
TypeError: string indices must be integers
I am trying to check if the last 4 bits of the string from an array were what I want them to be for the proper file type.
3
Answers
My Answer was opening the dictionary with the item
just because i was in the loop didnt mean i could use the item as an array when the item in the for loop was just a string,
So i had to reopen the dictionary with the item
json.load
returns the toplevel object in the JSON file – which in your case is adict
. Iterating over adict
directly gives you strings (the keys of thedict
).Replace the
for
loop line withfor key, item in movielist.items():
. Your code would become:TL, DR – here’s a fix
Explanation:
‘movielist’ is a dictionary. To iterate through it you need to use .keys(), .values() or .items().