Edit:
@Selcuk was right. Fetched data from the wrong Endpoint.
Following JSON:
{
"end": 2,
"items": [
{
"stats": {
"Game": "game1",
"Map": "snow",
"Region": "EU"
}
},
{
"stats": {
"Game": "game2",
"Map": "desert",
"Region": "EU"
}
}
],
"start": 0
}
If I understood correctly, "items" in this case is an array with various (2) "stats" objects containing the name/value pairs. I want to access every name/value pair with name "Map". So I tried the following:
if response.status_code == 200:
data = response.json()
for item in data["items"]:
map_value = item["stats"]["Map"]
print(map_value)
else:
print("Error.", response.status_code)
Unfortunately I get the following error
map_value = item["stats"]["Map"]
~~~~^^^^^^^^^
KeyError: 'stats'
I tried different versions with an index [0]["Map"]
or the .get("Map")
Function, but nothing helped.
Whats the correct way to handle this?
3
Answers
Can you check if items disct conatins the no of item objects expected and then to see if map object is available in item object.
Try this piece of code it will resolve the issue
Code seems to be right just you are not checking for condition if your expected key is present in response json or not!!
(KeyError means key is not present in json may be one of from ‘stats’ or ‘map’ is not present)