繁体   English   中英

TypeError:列表索引必须是整数,而不是Python中的str

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

我在过去的2天中一直遇到这个问题,但无法解决。

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)

我得到错误:

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是字典的列表,每个字典都包含一个name 要全部打印出来,可以执行print([data['name'] for data in jsondata_uuid])

提示:使用请求代替urllib

您的jsondata_uuid包含具有以下内容的字典列表:

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

您想要哪个“名称”键?

更改行results = jsondata_uuid['name']results = jsondata_uuid ,你会看到结果。 然后,您可以想到一种对名称进行排序的方法。

jsondata_uuid是一个列表,您不能使用键从中获取项目,而可以使用数字。

如果它包含字典作为第一项,则可以使用以下命令从字典中获取值:

results = jsondata_uuid[0]['name']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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