[英]Getting Keyerror when accessing an element in JSON, python
I've seen this asked a multitude of times, but I think the JSON I'm looking to access is a bit different.我已经多次看到这个问题,但我认为我想要访问的 JSON 有点不同。 I'm looking at a JSON with this format:我正在查看具有以下格式的 JSON:
{
"timestamp": 1589135576,
"level": 20,
"gender": "Male",
"status": {},
"personalstats": {},
"attacks": {
"103307874": {
"code": "cc7bc5ab6fbd54f49a2e879c49e70183",
"result": "Mugged",
"chain": 2,
"modifiers": {
"fairFight": 3,
"war": 1,
}
},
"103320473": {
"code": "3184c1e2c9662fd70a21f03a637cb02e",
"result": "Mugged",
"chain": 1,
"modifiers": {
"fairFight": 1.07,
"war": 1,
}
},
}
}
There are 98 more "attack" below the first two here.这里的前两个下面还有98个“攻击”。
Now I thought I could access the first attacks result with this code, but it results in a key error.现在我想我可以用这段代码访问第一个攻击结果,但它会导致一个关键错误。 Anyone understand why?有谁明白为什么?
currentresponse = requests.get("URL")
json_obj = json.loads(currentresponse.text)
lastresult = json_obj["attacks"][0]["result"]
As a "bonus" I can access the result of the attack through the following code.作为“奖励”,我可以通过以下代码访问攻击的结果。
json_obj["attacks"]["103320473"]["result"]
Yeah, you can't access with json_obj["attacks"][0]
, because it's not a list, and hence doesn't have indexing like a list.是的,您无法使用json_obj["attacks"][0]
访问,因为它不是列表,因此没有像列表那样的索引。 These are nested dicts, so you have to access them by dict rules (access by key
)这些是嵌套的字典,因此您必须通过字典规则访问它们(通过key
访问)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.