Python JSON KeyError,用于正在解析的对象中未缺少的密钥
我正在使用Python(2.X)对从RiotGames LoL API获取的JSON数据进行爬网和解析,并且遇到了一个奇怪的错误 我正在加载json数据,并通过attr读取数据attr,这非常好,直到我找到某个attr,它显然位于我试图从中提取它的对象中,但使Python抛出一个keyrerror,如下面的屏幕截图所示 下面是发生错误的代码段。如您所见,我打印对象(用于调试目的),然后解析所有attr,这可以正常工作,但由于未知原因在attr“doubleKills”处抛出一个KeyError。希望你们能帮忙^^Python JSON KeyError,用于正在解析的对象中未缺少的密钥,python,json,parsing,keyerror,Python,Json,Parsing,Keyerror,我正在使用Python(2.X)对从RiotGames LoL API获取的JSON数据进行爬网和解析,并且遇到了一个奇怪的错误 我正在加载json数据,并通过attr读取数据attr,这非常好,直到我找到某个attr,它显然位于我试图从中提取它的对象中,但使Python抛出一个keyrerror,如下面的屏幕截图所示 下面是发生错误的代码段。如您所见,我打印对象(用于调试目的),然后解析所有attr,这可以正常工作,但由于未知原因在attr“doubleKills”处抛出一个KeyError
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
您发布的终端上的JSON看起来好像来自
stats
,但您正在尝试使用participant
上的键
print 'doubleKills' in stats.keys()
应该计算为
True
将其包装在try:。。除KeyError外:打印列表(参与者)
-查看有什么?OMFG。。。我已经盯着代码看了很长时间了。。我怎么可能没看到呢。。有时候你需要的只是别人评估你的代码。。谢谢你说得对,这应该不止一次发生在我身上:D.就像校对一样!