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

如何在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")

核心逻辑说明

  1. 先将API响应解析为JSON数组格式
  2. 两层遍历:先遍历所有电站条目,再遍历每个电站下的机组单元
  3. 匹配到目标generatorName时,立即提取对应的componentId并终止遍历
  4. 生成器写法会直接返回第一个匹配结果,若没有匹配项则触发StopIteration,可在此处添加异常处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 10:45:56