如何使用上一个键解析json文件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用上一个键解析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
有必要在循环中运行所有这些词典列表,并确定每个团队销毁的营房数量。
答案
鉴于此,正如您所说,“匹配['目标']包含字典列表”,那么您的问题是您进行了额外的迭代。如果你试图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
循环时,它将遍历字典的键,然后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
以上是关于如何使用上一个键解析json文件?的主要内容,如果未能解决你的问题,请参考以下文章