skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Try this piece of code it will resolve the issue

    items = json_data["items"]
    for item in items:
        # Accessing the "stats"
        stats = item["stats"]
        
       "stats" dictionary
        game = stats["Game"]
        map = stats["Map"]
        region = stats["Region"]
        
        # Print vvalues
        print("Game:", game)
        print("Map:", map)
        print("Region:", region)
    
    Login or Signup to reply.
  3. 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)

    if response.status_code == 200:
        data = response.json()
        for item in data["items"]:
            map_value = item.get("stats",{}).get("No Map Data") # you can also check if 'map' in item['stats'] and continue loop.
            print(map_value)
    else:
        print("Error.", response
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search