Reputation: 13
I am trying to figure out how to get certain data from twitter after doing a request.
import requests
import json
username = input("Twitter Lookup: ")
url = "https://api.twitter.com/1.1/users/lookup.json?screen_name=" + username
page = requests.get(url, headers={"Authorization":"my auth here"})
account = (page.json())
print(account['id'])
After I do this, it gives me the error: TypeError: list indices must be integers or slices, not str
The data shown when I print(account):
Twitter Lookup: random=
[{'id': 172831776, 'id_str': '172831776', 'name': 'Random', 'screen_name': 'random', 'location': '', 'description': 'Learn something new today.'}] and so on
Is there any way to get around this?
Upvotes: 1
Views: 74
Reputation: 611
A Json Array is also a valid json object in python.
Your account object could look something like this:
[
{
"id": "<some_id>",
},
{
"id": "<some_id>",
}
]
In which case you should try to access:
account[0]['id']
or whatever other index you are looking for
Upvotes: 0
Reputation: 4789
You have to select the data like this.
account
is a list of dictionaries, so you have to first select the dictionary and then get the id
account = [{'id': 172831776, 'id_str': '172831776', 'name': 'Random', 'screen_name': 'random', 'location': '', 'description': 'Learn something new today.'}]
print(account[0]['id'])
print(account[0]['description'])
172831776
Learn something new today.
Upvotes: 2