【问题标题】:TypeError: string indices must be integersTypeError:字符串索引必须是整数
【发布时间】:2016-01-30 23:06:28
【问题描述】:

您好,我的代码有一个问题,我在一个循环中出现错误,该循环工作了几次,但随后给我一个 typeerro:字符串索引必须是整数。 我想调用一个 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

但只有在函数中的循环运行了几次之后。我不知道我做错了什么。任何帮助都会很好。

这里是 json 的链接:https://euw.api.pvp.net/api/lol/euw/v2.2/match/2492271473?api_key=c6ea2f68-7ed6-40fa-9b99-fd591c55c05f

【问题讨论】:

    标签: json python-3.x


    【解决方案1】:

    错误出现在

                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': &lt;default value&gt;}。否则,返回None 并将循环更改为

                info = self.get_match(gameids)
                if info is not None:
                    # as before
                else:
                    # whatever default action you want
    

    【讨论】:

      猜你喜欢
      • 2021-03-28
      • 2021-04-28
      • 2020-06-24
      • 2016-03-26
      • 2017-09-07
      • 2018-08-19
      • 2016-02-17
      • 2023-03-03
      相关资源
      最近更新 更多