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

遍历requests获取的API JSON数据 统计active冷却阶段数量

报错解决与需求实现方案

报错根因

原代码直接遍历接口返回的顶层字典所有键值对,第一次迭代拿到的是('status', 'read_success'),此时循环变量接收的data实际是字符串类型的read_success,字符串没有.items()方法,因此抛出AttributeError: 'str' object has no attribute 'items'。

接口返回结构是固定的,冷却阶段数据统一存在顶层的data字段下,不需要遍历顶层所有键,直接取该字段处理即可。

正确实现代码

import requests

# 提前定义好的请求参数
# my_rtu_read = {...}

def read_compressors():
    resp = requests.get('http://10.200.200.223:5000/bacnet/read/multiple', json=my_rtu_read)
    print(f"请求HTTP状态码: {resp.status_code}")
    # 校验HTTP请求状态,非2xx状态直接抛错,避免请求失败时解析异常
    resp.raise_for_status()
    return resp.json()

# 业务逻辑处理
resp = read_compressors()
print("接口完整返回:", resp)

active_counter = 0
# 直接取data字段,缺省返回空字典避免报错
stage_map = resp.get('data', {})
for stage_name, stage_detail in stage_map.items():
    if stage_detail.get('pv') == 'active':
        active_counter += 1
        print(f"检测到启用阶段: {stage_name}")

print(f"pv为active的cooling_stage总数: {active_counter}")

实现说明

  • 新增HTTP状态校验,接口请求异常(比如服务不可用、权限错误)时会提前抛出错误,不会走到后续JSON解析逻辑
  • 直接固定取data字段做遍历,完全规避把字符串类型的status值当字典处理的问题
  • 用.get()方法取字段值,就算个别冷却阶段缺失pv字段、或者接口返回无data字段,也不会触发KeyError
  • 自动适配data下任意数量的冷却阶段,不需要提前硬编码阶段总数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:39:21