Search code examples
pythonjsonparsingkeyerror

Python JSON KeyError for key that is not missing in object being parsed


I'm crawling and parsing the JSON data I'm getting from RiotGames LoL API using Python (2.X) and I'm running into an odd error.

I'm loading in the json data and reading the data attr by attr, which goes great until I hit a certain attr which is clearly in the object I'm trying to extract it from but makes Python throw a KeyError as can be seen in the screenshot below.

enter image description here Here is the codesnippet where the error takes place. As you can see I print the object (for debugging purposes) and then parse all attr, which works fine but throws a KeyError for unknown reasons at the attr 'doubleKills'. Hope you guys can help ^^

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

Solution

  • It looks as though the JSON on the Terminal you posted is from stats, but you are trying to use the key on participant.

    print 'doubleKills' in stats.keys()
    

    Should evaluate to True