I get this error (TypeError: list indices must be integers or slices, not str) when trying to request something in square brackets. I've searched on this website and other ones a lot. I've tried [0]. The real problem is that ["data"]
and ["fortnite"]
are not in square brackets, ["posts"]
opens the square brackets and ["title"]
, ["description"]
, ["author"]
and ["url"]
are in the square brackets.
compareblog = requests.get("https://fn-api.com/api/blogposts")
comparename = compareblog.json()["data"]["fortnite"]["posts"]["title"]
count = 1
initialcheckdelay = 3
checkdelayafter = 60
while 1:
print(f'Waiting for blog changes -> [Count: {count}]\n')
blog = requests.get("https://fn-api.com/api/blogposts")
yesyes = [int(blog.json())]
name = yesyes["data"]["fortnite"]["posts"]["title"]
desc = yesyes["data"]["fortnite"]["posts"]["description"]
author = yesyes["data"]["fortnite"]["posts"]["author"]
link = yesyes["data"]["fortnite"]["posts"]["url"]
time.sleep(initialcheckdelay)
count = count 1
if comparename != name:
while 2:
print(f"Blog change detected!")
api.update_status(f"New Blog Post has been detected by {author}!\n\n{name}\n{desc}\nLink: {link}") #This is a Tweet
sleep(checkdelayafter)
This is the error I get after running this:
Traceback (most recent call last):
File {filename}, line 114, in <module>
blog_check()
File {filename}, line 77, in blog_check
comparename = compareblog.json()["data"]["fortnite"]["posts"]["title"]
TypeError: list indices must be integers or slices, not str
CodePudding user response:
The field 'posts'
is a list of dicts. Each of those dicts contain a key, 'title'
. To retrieve the value of a title, you need to select an individual post from the posts
list.
posts = compareblog.json()["data"]["fortnite"]["posts"]
first_post = posts[0]
title = first_post["title"]