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
相关产品推荐
相关产品推荐

