简体   繁体   中英

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. I'm looking at a JSON with this format:

{
  "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.

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. These are nested dicts, so you have to access them by dict rules (access by key )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM