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

Python如何从JSON结构中批量提取children数组内的所有firstName值

实现方案

首先要避免重复调用json.loads解析JSON,重复解析会严重浪费性能,先将解析结果存储为变量后再遍历取值即可,两种实现方式如下:

方式1:列表推导式(推荐,大数据量下性能更高)

import json

# 仅执行1次JSON解析
parsed_data = json.loads(children.text)
# 直接遍历children数组提取所有firstName
firstNames = [child["firstName"] for child in parsed_data["children"]]

方式2:普通for循环(可读性更高)

import json

parsed_data = json.loads(children.text)
firstNames = []
for child in parsed_data["children"]:
    firstNames.append(child["firstName"])

可选容错处理

如果数据中存在部分子项缺失firstName字段的情况,可以加判断避免抛出KeyError:

firstNames = [child["firstName"] for child in parsed_data["children"] if "firstName" in child]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:06:02