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

Python从GitHub接口返回的嵌套列表中提取字段报错怎么解决

报错原因

你请求的https://api.github.com/users/mralexgray/repos接口返回的顶层数据是仓库数组(列表),并非字典,直接用j['owner']尝试用字符串索引访问列表,就会触发类型错误。

数据结构说明

列表中的每一个元素对应单个仓库的字典对象,你需要的字段取值路径如下:

  • owner login:仓库对象['owner']['login']
  • owner key(即owner id):仓库对象['owner']['id']
  • license key:仓库对象['license']['key'](无开源许可证时license字段为None,需判空)
  • license name:仓库对象['license']['name'](无开源许可证时license字段为None,需判空)

正确实现代码

import requests
from datetime import datetime

url = 'https://api.github.com/users/mralexgray/repos'
# 发起请求并直接转JSON格式
repo_list = requests.get(url).json()

# 定义时间筛选阈值
threshold_date = datetime.strptime('2013-06-04', '%Y-%m-%d').date()

for repo in repo_list:
    # 转换仓库创建时间为日期对象用于对比
    create_date = datetime.strptime(repo['created_at'], '%Y-%m-%dT%H:%M:%SZ').date()
    if create_date >= threshold_date:
        # 提取owner相关字段
        owner_login = repo['owner']['login']
        owner_id = repo['owner']['id']
        # 处理无许可证的空值场景
        license_key = repo['license']['key'] if repo.get('license') else '无许可证'
        license_name = repo['license']['name'] if repo.get('license') else '无许可证'
        # 输出结果
        print(f"owner login:{owner_login}")
        print(f"owner key:{owner_id}")
        print(f"license key:{license_key}")
        print(f"license name:{license_name}")
        print('-' * 40)

内容的提问来源于stack exchange,提问作者Shaon Paul

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:06:00