Reputation: 69
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"]
Upvotes: 0
Views: 121
Reputation: 11134
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
)
Upvotes: 1