Python JSON KeyError,用于分析的对象中不缺少的键

2024-10-01 17:31:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python(2.X)对从RiotGames LoL API获取的JSON数据进行爬网和解析,遇到了一个奇怪的错误。在

我正在加载json数据并逐属性读取数据attr,这非常好,直到我找到了一个attr,它显然位于我试图从中提取它的对象中,但却导致Python抛出一个KeyError,如下面的屏幕截图所示。在

enter image description here 下面是发生错误的代码片段。如您所见,我打印对象(用于调试目的),然后解析所有attr,这很好,但是由于未知原因在attr“doubleKills”处抛出一个keyror。希望你们能帮忙

def parseJSON(self, jsonDump):
    matchDetailDict =  dict()
    jsonobj = json.loads(jsonDump)

    matchId = jsonobj['matchId']
    tmpMatch = Match()
    tmpMatch.matchID = matchId

    tmpMatch.creationDate = jsonobj['matchCreation']
    tmpMatch.matchDuration = jsonobj['matchDuration']

    for participant, participantId in zip(jsonobj['participants'], jsonobj['participantIdentities']):
        stats = participant['stats']
        print stats
        tmpStats = MatchPlayerStats()
        tmpStats.playerID = participantId['player']['summonerId']
        tmpStats.matchID = matchId
        tmpStats.winner = stats['winner']
        tmpStats.kills = stats['kills']
        tmpStats.deaths = stats['deaths']
        tmpStats.assists = stats['assists']
        tmpStats.kda = (tmpStats.kills + tmpStats.assists)*1.0/max(tmpStats.deaths, 0.5) 
        tmpStats.visionWardsBoughtInGame = stats['visionWardsBoughtInGame']
        tmpStats.sightWardsBoughtInGame = stats['sightWardsBoughtInGame']
        tmpStats.championID = participant['championId']
        tmpStats.doubleKills = participant['doubleKills'] #KeyError here!
        tmpStats.firstBloodAssist = participant['firstBloodAssist']
        tmpStats.firstBloodKill = participant['firstBloodKill']
        tmpStats.killingSprees = participant['killingSprees']
        tmpStats.wardsKilled = participant['wardsKilled']
        tmpStats.wardsPlaced = participant['wardsPlaced']
        tmpStats.unrealKills = participant['unrealKills']

        matchDetailDict[tmpStats.playerID] = tmpStats

    tmpMatch.playerStats = matchDetailDict
    return tmpMatch

Tags: 数据jsonstats错误attrparticipantkillsdeaths

热门问题