如何用Python从pytest的API响应JSON中提取所有hpsId和powerPlant id?
解决方案
首先假设你的API返回的JSON结构是一个包含多个对象的数组,每个对象里包含hpsId字段和嵌套的powerPlant.id字段,类似这样:
[ { "hpsId": "hps_001", "powerPlant": {"id": "pp_001", "name": "电厂A"}, "otherField": "xxx" }, { "hpsId": "hps_002", "powerPlant": {"id": "pp_002", "name": "电厂B"}, "otherField": "yyy" } ]
你可以通过遍历响应数组来提取所有目标字段,下面是几种常用的存储方式和对应的代码实现:
方式1:存储为字典列表(保留完整映射关系)
这种方式适合需要同时使用hpsId和powerPlant.id的场景,每个元素是一个包含两个字段的字典:
import requests import pytest # 可以把这个逻辑放在pytest fixture里,供多个测试用例复用 @pytest.fixture(scope="module") def extract_all_ids(): # 调用API获取响应 response = requests.get("你的API地址") response.raise_for_status() # 确保请求成功 json_data = response.json() # 遍历所有元素,提取目标字段 id_list = [] for item in json_data: # 注意处理可能的字段缺失情况,避免KeyError hps_id = item.get("hpsId") pp_id = item.get("powerPlant", {}).get("id") if hps_id and pp_id: # 只保留两个字段都存在的条目 id_list.append({ "hpsId": hps_id, "powerPlantId": pp_id }) return id_list # 测试用例中使用 def test_use_extracted_ids(extract_all_ids): # 打印查看结果 print(extract_all_ids) # 后续请求可以遍历这个列表取参数 for ids in extract_all_ids: params = { "hps_id": ids["hpsId"], "pp_id": ids["powerPlantId"] } # 发起后续请求 # response = requests.post("后续接口地址", params=params)
方式2:存储为两个独立列表(分别存hpsId和powerPlant.id)
如果后续请求只需要单独使用其中一类ID,或者需要按索引对应,可以用两个列表:
@pytest.fixture(scope="module") def separate_id_lists(): response = requests.get("你的API地址") response.raise_for_status() json_data = response.json() hps_ids = [] pp_ids = [] for item in json_data: hps_id = item.get("hpsId") pp_id = item.get("powerPlant", {}).get("id") if hps_id and pp_id: hps_ids.append(hps_id) pp_ids.append(pp_id) return hps_ids, pp_ids # 使用示例 def test_use_separate_lists(separate_id_lists): hps_ids, pp_ids = separate_id_lists print("所有hpsId:", hps_ids) print("所有powerPlant id:", pp_ids)
方式3:存储为映射字典(用hpsId做键,powerPlant.id做值)
如果需要通过hpsId快速查找对应的powerPlant.id,可以用字典映射:
@pytest.fixture(scope="module") def id_mapping(): response = requests.get("你的API地址") response.raise_for_status() json_data = response.json() mapping = {} for item in json_data: hps_id = item.get("hpsId") pp_id = item.get("powerPlant", {}).get("id") if hps_id and pp_id: mapping[hps_id] = pp_id return mapping # 使用示例 def test_use_mapping(id_mapping): print("hpsId到powerPlant id的映射:", id_mapping) # 根据hpsId取对应值 pp_id = id_mapping.get("hps_001")
注意事项
- 用
item.get()替代直接索引item["hpsId"],可以避免字段缺失时抛出KeyError,让代码更健壮。 - 根据你的pytest用例范围需求,设置fixture的
scope(比如module表示整个模块只执行一次,提升效率)。 - 如果API响应是嵌套更深的结构,只需调整字段的提取路径即可。
内容的提问来源于stack exchange,提问作者Magnus Jensen
相关产品推荐
相关产品推荐

