
本文介绍如何使用 Python 从嵌套 JSON 响应中高效提取全部 hpsId 和 powerPlant.id 字段值,并以列表、元组或字典等形式结构化存储,便于后续 API 测试中复用。
本文介绍如何使用 python 从嵌套 json 响应中高效提取全部 `hpsid` 和 `powerplant.id` 字段值,并以列表、元组或字典等形式结构化存储,便于后续 api 测试中复用。
在自动化测试(如 pytest)中,常需从 API 返回的大规模 JSON 数据中批量提取关键标识符(如 hpsId 和 powerPlant.id),用于驱动后续参数化请求。直接通过索引 response.json()[0]["hpsId"] 只能获取单条记录,而实际响应通常包含数百甚至上千个对象——此时必须采用迭代方式遍历整个数据结构。
以下为推荐的三种实现方式,均基于 response.json() 解析后的 Python 列表(即顶层 JSON 数组):
调用 Cutout.Pro 视觉处理 API 进行背景移除、人像抠图和照片增强,支持文件上传与图片 URL 输入。
✅ 方式一:显式 for 循环(清晰易调试)
data = response.json()
all_hps_ids = []
all_powerplant_ids = []
for item in data:
try:
hps_id = item["hpsId"]
pp_id = item["powerPlant"]["id"]
all_hps_ids.append(hps_id)
all_powerplant_ids.append(pp_id)
except (KeyError, TypeError) as e:
print(f"跳过异常项(缺少字段或类型错误): {e}")
continue
print("所有 hpsId:", all_hps_ids)
print("所有 powerPlant.id:", all_powerplant_ids)
✅ 方式二:列表推导式(简洁高效)
data = response.json()
all_hps_ids = [item["hpsId"] for item in data]
all_powerplant_ids = [item["powerPlant"]["id"] for item in data]
# 同时提取并配对(返回 [(hpsId1, ppId1), (hpsId2, ppId2), ...])
all_pairs = [(item["hpsId"], item["powerPlant"]["id"]) for item in data]
# 构建映射字典(hpsId → powerPlant.id)
id_mapping = {item["hpsId"]: item["powerPlant"]["id"] for item in data}
⚠️ 注意:列表推导式简洁但缺乏容错能力。若部分对象缺失 hpsId 或 powerPlant,将触发 KeyError。生产环境建议搭配 try/except 或使用 dict.get() 安全访问:
all_hps_ids = [item.get("hpsId") for item in data if item.get("hpsId") is not None] all_powerplant_ids = [ item.get("powerPlant", {}).get("id") for item in data if item.get("powerPlant", {}).get("id") is not None ]
✅ 方式三:集成到 pytest 测试函数中(实用示例)
def test_get_powerplant():
response = get_requests(token, '/mfrr-eam/api/mfrr/eam/powerplant/all')
assert response.status_code == 200
data = response.json()
# 安全提取全部 ID(带异常处理)
hps_ids = []
pp_ids = []
for item in data:
try:
hps_ids.append(item["hpsId"])
pp_ids.append(item["powerPlant"]["id"])
except KeyError as e:
pytest.skip(f"跳过不完整数据项(缺失字段 {e})")
# 存储为模块级变量或 fixture 返回值,供后续测试使用
setattr(test_get_powerplant, "all_hps_ids", hps_ids)
setattr(test_get_powerplant, "all_pp_ids", pp_ids)
print(f"共提取 {len(hps_ids)} 个 hpsId,{len(pp_ids)} 个 powerPlant.id")
? 最佳实践建议
- 优先使用 list comprehension + .get() 组合:兼顾简洁性与健壮性;
- 避免全局变量:推荐通过 pytest fixture 管理提取结果,提升可维护性与并发安全性;
- 验证数据完整性:提取后建议断言非空 assert hps_ids,防止空响应导致下游测试静默失败;
- 考虑性能:对超大规模 JSON(>10k 条),可结合生成器表达式或流式解析(如 ijson)降低内存占用。
通过上述方法,你不仅能可靠地批量提取所需字段,还能灵活适配不同测试场景——无论是参数化请求、数据校验,还是构建测试上下文,都具备良好的扩展性与可读性。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










