如何在Pytest的API返回JSON中按发电机名称提取componentId
根据发电机名称提取componentId的实现方法
你需要遍历API返回的JSON数组结构,逐层查找匹配指定发电机名称的units项,再提取对应的componentId。原思路里的层级有误,componentId并不在hpsId节点下,而是嵌套在powerPlant.units数组的元素中。
基础循环实现代码
# 解析API响应为JSON数据 json_data = response.json() # 定义要查找的目标发电机名称 target_generator = "Stølsdal G1" component_id = None # 遍历外层的电站条目 for plant_item in json_data: # 遍历当前电站下的所有机组单元 for unit in plant_item["powerPlant"]["units"]: if unit["generatorName"] == target_generator: component_id = unit["componentId"] break # 找到目标后退出机组遍历 if component_id: break # 找到目标后退出电站遍历 # 使用获取到的componentId print(component_id) # 输出结果:166051
简洁生成器写法
如果想简化代码,可以用生成器表达式直接匹配第一个符合条件的项:
json_data = response.json() target_generator = "Stølsdal G1" try: component_id = next( unit["componentId"] for plant_item in json_data for unit in plant_item["powerPlant"]["units"] if unit["generatorName"] == target_generator ) except StopIteration: # 处理未找到目标发电机的场景 component_id = None print(f"未找到发电机 {target_generator} 对应的componentId")
核心逻辑说明
- 先将API响应解析为JSON数组格式
- 两层遍历:先遍历所有电站条目,再遍历每个电站下的机组单元
- 匹配到目标
generatorName时,立即提取对应的componentId并终止遍历 - 生成器写法会直接返回第一个匹配结果,若没有匹配项则触发
StopIteration,可在此处添加异常处理逻辑
内容的提问来源于stack exchange,提问作者Magnus Jensen
相关产品推荐
相关产品推荐

