You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历API返回的JSON字典时触发TypeError错误排查

问题:处理NBA赛事API响应时触发TypeError错误

我通过GET请求获取NBA赛事列表,遍历JSON响应处理数据时,teams_array = item['teams']之前的内容能正常打印,但之后触发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()

最初我直接用for item in response_data['response']循环,没用到games_data变量,还是出现相同错误。

代码输出

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

JSON样本数据

{
  "response": [
    {
      "id": 194266,
      "date": "2022-10-02T23:00:00+00:00",
      "time": "23:00",
      "timestamp": 1664751600,
      "timezone": "UTC",
      "stage": null,
      "week": null,
      "status": {},
      "league": {},
      "country": {},
      "teams": {
        "home": {
          "id": 142,
          "name": "Houston Rockets",
          "logo": "https://media.apisports.io/basketball/teams/142.png"
        },
        "away": {
          "id": 158,
          "name": "San Antonio Spurs",
          "logo": "https://media.apisports.io/basketball/teams/158.png"
        }
      }
    }
  ]
}

注:response键之前还有其他我不需要的数据。


解决方案

问题核心是你误解了item['teams']的数据类型:它是一个字典,不是数组(列表)。当你用for teams in teams_array遍历字典时,Python默认会遍历字典的键名(也就是字符串"home"和"away"),此时teams是字符串,自然无法用teams['away']这种方式取值,才会抛出string indices must be integers错误。

直接从字典中取出home和away即可,不需要遍历:

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 = item['teams']
        # 直接从字典中取出主客场球队
        print(f"{teams['away']['name']} @ {teams['home']['name']}")

get_nba_games()

内容的提问来源于stack exchange,提问作者Matthew Jarrett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 08:57:14