嗨我的代码有问题,我在一个循环中得到一个错误,但是然后抛出一个typeerro:string索引必须是整数。 我想调用api来获取json并获取json响应的一些部分。继承人代码:
class API(object):
def __init__(self, api_key):
self.api_key = api_key
def _request(self, api_url, params={}):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
url=api_url
),
params=args
)
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
print(response.url)
def get_list(self):
excel = EXCEL('s6.xlsx')
api_url = Consts.URL['list'].format(
version = Consts.API_VERSIONS['matchversion'],
start = excel.get_gamenr()
)
return self._request(api_url)
def get_match(self, matchid):
idlist = matchid
api_url = Consts.URL['match'].format(
version = Consts.API_VERSIONS['matchversion'],
matchId = idlist
)
return self._request(api_url)
def match_ids(self):
api = API('c6ea2f68-7ed6-40fa-9b99-fd591c55c05f')
x = api.get_list()
y = x['matches']
count = len(y)
ids = []
while count > 0:
count = count - 1
temp = y[0]
ids.append(temp['matchId'])
del y[0]
return ids
def match_info(self):
matchids = self.match_ids()
print(matchids)
matchinfolist = {}
counter = 1
for gameids in matchids:
info = self.get_match(gameids)
myid = self.find_partid(info['participantIdentities'])
prepdstats = info['participants'][myid-1]
print(prepdstats)
matchinfolist['stats' + str(counter)] = prepdstats
return matchinfolist
def find_partid(self, partlist):
partid = 0
idlist = partlist
while partid < 10:
partid = partid + 1
tempplayer = idlist[0]['player']
if tempplayer['summonerId'] == 19204660:
playernr = partid
partid = 500
del idlist[0]
return playernr
当我运行match_info()函数时,我收到此错误
Traceback (most recent call last):
File "C:\Users\Niklas\Desktop\python riot\main.py", line 17, in <module>
main()
File "C:\Users\Niklas\Desktop\python riot\main.py", line 10, in main
print(api.match_info())
File "C:\Users\Niklas\Desktop\python riot\api.py", line 78, in match_info
myid = self.find_partid(info['participantIdentities'])
TypeError: string indices must be integers
但仅在函数中的循环运行了几次之后。我不知道我做错了什么。任何帮助都会很好。
答案 0 :(得分:0)
错误显示在
上 myid = self.find_partid(info['participantIdentities'])
要执行此行,info必须是带字符串键的映射,而不是字符串本身。 info
是
info = self.get_match(gameids)
get_match
以
return self._request(api_url)
_request
以
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
对于要运行的循环,response.json()
必须是带有键'participantIdentities'
的词典。你的错误是期待永远是真的。
一种解决方法可能是让期望始终如一。如果存在令人满意的默认值,请返回{'participantIdentities': <default value>}
。否则,返回None
并将循环更改为
info = self.get_match(gameids)
if info is not None:
# as before
else:
# whatever default action you want