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

如何提取JSON字典列表中groupId的取值?解决KeyError报错

解决KeyError: 'items'并提取所有groupId

你的代码报错是因为**items字段并不在根层级的groups对象里**,而是嵌套在groups字段内部的对象中。从你给出的JSON结构来看,正确的层级是:根对象 → groups → items,而你直接尝试访问groups['items'],自然会找不到这个键。

修正后的代码示例

result = session.get(urljoin(baseurl, path), headers=headers, verify=False)
groups_data = result.json()

# 正确获取items列表
group_items = groups_data['groups']['items']

# 提取所有groupId到列表
group_ids = [item['groupId'] for item in group_items]
print(group_ids)

# 如果要输出键值对格式(groupName: groupId)
for item in group_items:
    print(f"{item['groupName']}: {item['groupId']}")

代码说明

  • 核心修正点:通过groups_data['groups']['items']定位到正确的分组列表,这是你之前代码的错误根源
  • 用列表推导式可以快速生成所有groupId的列表,简洁高效
  • 遍历items时,直接通过item['groupId']就能获取对应值,无需嵌套循环遍历item的所有键

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 08:01:00