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

如何用Python解析嵌套JSON提取id并解决列表索引类型报错

代码修改方案

错误原因

  • 接口返回的JSON根节点是列表类型,无法直接用字符串user作为索引取值
  • 字典的get()是调用方法,需要使用圆括号传递参数,不能用方括号

修正后可运行代码

import requests
headers = {
    "Authorization": "你的Discord授权Token"
}
r = requests.get("https://discordapp.com/api/v6/users/@me/relationships", headers=headers)
# requests自带json解析方法,无需手动调用json.loads
rjson = r.json()
for rel_item in rjson:
    # 先取关系项中的user字段,再提取id
    user_info = rel_item.get("user")
    if user_info:
        print(user_info.get("id"))

补充说明

如果你的需求是提取每个关系项外层的id字段,而非用户信息内的id,直接打印rel_item.get("id")即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:18:02