简体   繁体   中英

TypeError: list indices must be integers, not str in Python

I have been having this problem for the last 2 days and i can't fix it.

import urllib.request
import json
import base64
name = "koalaaaa"
url = "https://api.mojang.com/users/profiles/minecraft/" + name
rawdata = urllib.request.urlopen(url)
newrawdata = rawdata.read()
jsondata = json.loads(newrawdata.decode('utf-8'))
results = jsondata['id']
url_uuid = "https://api.mojang.com/user/profiles/" + results + "/names"
rawdata_uuid = urllib.request.urlopen(url_uuid)
newrawdata_uuid = rawdata_uuid.read()
jsondata_uuid = json.loads(newrawdata_uuid.decode('utf-8'))
results = jsondata_uuid['name']
print (results)

and i get the error:

Traceback (most recent call last):
File "C:/Python34/unmigrated.py", line 14, in <module>
results = jsondata_uuid['name']
TypeError: list indices must be integers, not str

jsondata_uuid is a list of dicts, each of which contains a name . To print them all out you can do print([data['name'] for data in jsondata_uuid]) .

Tip: Use requests instead of urllib .

Your jsondata_uuid contains a list of dictionaries with something like this:

[{'name': 'Deamti'}, {'changedToAt': 1423576506000, 'name': 'ChocolateBanana'}, {'changedToAt': 1426793965000, 'name': 'IMBHARLOW'}, {'changedToAt': 1430137396000, 'name': 'SuckUp'}, {'changedToAt': 1437970183000, 'name': 'lllllll'}, {'changedToAt': 1440592843000, 'name': 'Koalaaaa'}]

Which 'name' key you want?

Change the line results = jsondata_uuid['name'] for results = jsondata_uuid and you will see the results. Then, you can think of a way of sorting the names out.

jsondata_uuid is a list you cannot use a key to fetch items from it instead you can use numbers.

if it contains a dictionary as the first item you can fetch a value from the dictionary using this for example :

results = jsondata_uuid[0]['name']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM