Home > OS >  JSON - Iterating over dictionary throws error
JSON - Iterating over dictionary throws error

Time:08-05

I am trying to make a GET request to get a list of games by iterating over a JSON response. From the output, it looks like it was able to iterate and print everything up until teams_array = item['teams'], then it throws a TypeError.

import requests
import json
import pprint
from data.api import api


def get_nba_games():
    """Gets games schedule from requests"""
    url = "https://api-basketball.p.rapidapi.com/games"
    querystring = {"season": "2022-2023", "league": "12"}
    headers = {
        "X-RapidAPI-Key": api,
        "X-RapidAPI-Host": "api-basketball.p.rapidapi.com"
    }
    response = requests.request("GET", url, headers=headers, params=querystring)
    response_data = response.json()
    games_data = response_data['response']

    for item in games_data:
        print(item['date'])
        print(item['time'])
        print(item['timezone'])
        print(item['week'])
        teams_array = item['teams']
        for teams in teams_array:
            print(f"{teams['away']['name']} @ {teams['home']['name']}")

get_nba_games()

I first tried to use the for loop for item in response_data['response'] without the games_data variable, but it threw the same error.

Here is the output of the above code.

2022-10-02T23:00:00 00:00
23:00
UTC
None
Traceback (most recent call last):
  File "C:\Users\user\python\project\main.py", line 27, in <module>
    get_nba_games()
  File "C:\Users\user\python\project\main.py", line 25, in
get_nba_games
    print(f"{teams['away']['name']} @ {teams['home']['name']})
TypeError: string indices must be integers

Have I loaded the JSON response wrong?

Here is the sample data of the JSON

"response":[25 items
    0:{12 items
    "id":194266
    "date":"2022-10-02T23:00:00 00:00"
    "time":"23:00"
    "timestamp":1664751600
    "timezone":"UTC"
    "stage":NULL
    "week":NULL
    "status":{...}3 items
    "league":{...}5 items
    "country":{...}4 items
    "teams":{2 items
        "home":{3 items
            "id":142
            "name":"Houston Rockets"
            "logo":"https://media.apisports.io/basketball/teams/142.png"
            }
        "away":{3 items
            "id":158
            "name":"San Antonio Spurs"
            "logo":"https://media.apisports.io/basketball/teams/158.png"
            }
}

Note: There are other data that comes before the response key that I don't need.

CodePudding user response:

There is no teams arrray in your sample data, it's a dictionary. Remove the for loop and just do this:

import requests
import json
import pprint
from data.api import api


def get_nba_games():
    """Gets games schedule from requests"""
    url = "https://api-basketball.p.rapidapi.com/games"
    querystring = {"season": "2022-2023", "league": "12"}
    headers = {
        "X-RapidAPI-Key": api,
        "X-RapidAPI-Host": "api-basketball.p.rapidapi.com"
    }
    response = requests.request("GET", url, headers=headers, params=querystring)
    response_data = response.json()
    games_data = response_data['response']

    for item in games_data:
        print(item['date'])
        print(item['time'])
        print(item['timezone'])
        print(item['week'])
        teams_array = item['teams']
        print(f"{teams_array['away']['name']} @ {teams_array['home']['name']}")
            

get_nba_games()

CodePudding user response:

I figured it out!

Instead of making a new variable in the teams array, I changed the for loop to below:

    for item in games_data:
        print(item['date'])
        print(item['time'])
        print(item['timezone'])
        print(item['week'])
        print(f"{item['teams']['away']['name']} @ {item['teams']['home']['name']}")

I didn't need the team_array = item['teams']

  • Related