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

Python解析API返回JSON时列表取值报错,求解决方法

问题解决:列表索引错误处理

错误原因

periodesUniteLegale是由字典组成的列表,而非单个字典。你直接用字符串'denominationUniteLegale'作为索引,Python会提示类型错误,因为列表只能用整数或切片作为索引。

解决方案

根据你的需求,有两种常见处理方式:

1. 提取列表中第一个周期的名称(适用于只需要单条数据)

修改代码,先通过整数索引定位到列表中的字典,再提取字段:

import json

data = json.loads(api_call_response.text)
siren = data['uniteLegale']['siren']
categorieEntreprise = data['uniteLegale']['categorieEntreprise']
effectif = data['uniteLegale']['trancheEffectifsUniteLegale']
periodesUnite = data['uniteLegale']['periodesUniteLegale']

# 先判断列表非空,避免索引越界
if periodesUnite:
    denomination = periodesUnite[0]['denominationUniteLegale']
else:
    denomination = None  # 无数据时设置默认值,可根据需求调整

2. 提取所有周期的名称(适用于需要全部数据)

通过遍历列表,逐个提取每个字典中的字段:

import json

data = json.loads(api_call_response.text)
siren = data['uniteLegale']['siren']
categorieEntreprise = data['uniteLegale']['categorieEntreprise']
effectif = data['uniteLegale']['trancheEffectifsUniteLegale']
periodesUnite = data['uniteLegale']['periodesUniteLegale']

# 遍历收集所有名称,用列表推导式更简洁
denominations = [periode['denominationUniteLegale'] for periode in periodesUnite]

# 如果担心字段不存在,可用get方法设置默认值
denominations = [periode.get('denominationUniteLegale', '未知名称') for periode in periodesUnite]

额外提示

  • 处理列表时务必先判断是否为空,避免触发IndexError;
  • 若API返回的字典可能缺失目标字段,优先使用dict.get(key, 默认值)替代直接索引,避免KeyError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:15:43