如何使用上一个键解析json文件?

时间:2019-04-14 10:39:42

标签: python json

我有这样长的JSON(我需要找到每个团队销毁的营房数量):

[{'player_slot': 129,
  'slot': 6,
  'team': 3,
  'time': 2117.449,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
 {'player_slot': 132,
  'slot': 9,
  'team': 3,
  'time': 2156.047,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
 {'key': '512', 'time': 2178.992, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'},
 {'player_slot': 4,
  'slot': 4,
  'team': 2,
  'time': 2326.829,
  'type': 'CHAT_MESSAGE_TOWER_KILL'},
{'key': '2', 'time': 2333.384, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'}],
 {'key': '2', 'time': 2340.384, 'type': 'CHAT_MESSAGE_BARRACKS_KILL'}]

radiant_barracks_kills = 0
dire_barracks_kills = 0
for objective in match['objectives']:
    for i,e in enumerate(objective):
        if e['type'] == 'CHAT_MESSAGE_BARRACKS_KILL':
            if objective[i-1]['slot'] < 5:
                radiant_barracks_kills += 1
            if objective[i-1]['slot'] >= 5:
                dire_barracks_kills += 1

TypeError: string indices must be integers

有必要循环运行所有此类词典列表,并确定每个团队销毁的营房数量。

1 个答案:

答案 0 :(得分:0)

考虑到您所说的“ match ['objectives']包含字典列表”,那么您的问题是进行了额外的迭代。如果您尝试print的类型和值e

for objective in match['objectives']:
    for i,e in enumerate(objective):
        print(type(e), e)

您会得到:

<class 'str'> player_slot
<class 'str'> slot
<class 'str'> team
<class 'str'> time
<class 'str'> type
<class 'str'> player_slot
<class 'str'> slot
<class 'str'> team
<class 'str'> time
<class 'str'> type
...

第一个for循环已经在字典列表上进行迭代。因此objective已经是字典。当您将第二个for循环到enumerate时,它将迭代字典的 keys ,然后e['type']将失败,因为这就像您例如,"player_slot"['type'](导致“ TypeError:字符串索引必须为整数”)。

您只需要迭代一次。

radiant_barracks_kills = 0
dire_barracks_kills = 0
list_of_objectives = match['objectives']  # [{..},{..},..{..}]

for i, objective in enumerate(list_of_objectives):
    # objective is a dict
    if objective['type'] == 'CHAT_MESSAGE_BARRACKS_KILL':
        if list_of_objectives[i-1]['slot'] < 5:
            radiant_barracks_kills += 1
        if list_of_objectives[i-1]['slot'] >= 5:
            dire_barracks_kills += 1