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

Python如何提取JSON内所有对象的code字段?可批量指定下标取值吗?

批量提取JSON嵌套字段实现说明

你提到的json_response["items"][0, 1, 2]["country"]["code"]写法在原生Python语法中不被支持,方括号内传入多个数值会被识别为元组索引,而Python原生的列表、字典都不支持元组作为索引直接批量取值,该写法运行时会直接抛出类型错误或键错误。

你可以通过以下两种常用方式实现需求:

  • 方法1:列表推导式(无第三方依赖,最通用)
    要提取所有items对应country下的code值,写法如下:
# 假设已将JSON字符串反序列化为Python字典对象json_response
code_list = [item["country"]["code"] for item in json_response["items"]]
print(code_list)
# 输出结果:['kz', 'kz', 'kz']

如果仅需要提取下标0、1、2对应元素的code值,写法如下:

code_list = [json_response["items"][i]["country"]["code"] for i in [0, 1, 2]]

如果不确定目标字段是否存在,可使用dict.get()避免抛出KeyError:

# 字段不存在时默认返回None,也可传入第二个参数指定默认值
code_list = [item.get("country", {}).get("code", "缺省值") for item in json_response["items"]]
  • 方法2:结合operator.itemgetter批量取指定下标元素
    适合需要频繁批量提取固定位置元素的场景:
from operator import itemgetter

# 先批量取出下标为0、1、2的元素
target_items = itemgetter(0, 1, 2)(json_response["items"])
# 再提取对应code字段
code_list = [item["country"]["code"] for item in target_items]

内容的提问来源于stack exchange,提问作者Константин Морев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:02