首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环使用API JSON数据和计数状态‘

循环使用API JSON数据和计数状态‘
EN

Stack Overflow用户
提问于 2022-06-26 13:10:34
回答 1查看 27关注 0票数 -1

我从rest和函数的请求库中获取数据:

代码语言:javascript
复制
def read_compressors():

    x = requests.get('http://10.200.200.223:5000/bacnet/read/multiple',json=my_rtu_read)
    print(x.status_code)
    return x.json()

其中x看起来如下:

代码语言:javascript
复制
{'status': 'read_success', 'data': {'cooling_stage_1': {'pv': 'active'}, 'cooling_stage_2': {'pv': 'active'}, 'cooling_stage_3': {'pv': 'inactive'}, 'cooling_stage_4': {'pv': 'inactive'}}}

我如何循环通过data和计数所有冷却阶段,即active?在data中可能有很多阶段,但在本例中只有4,cooling_stage_1通过cooling_stage_4。希望这是合理的!

如果我调用该函数并试图遍历它:

代码语言:javascript
复制
x = read_compressors()
print("x is:",x)

temporary_counter = 0 #use this to count += active???
for status,data in x.items():
    print(data)
    
    for k,v in data.items():
        print(k,v)

此错误被删除:

代码语言:javascript
复制
200
x is: {'status': 'read_success', 'data': {'cooling_stage_1': {'pv': 'inactive'}, 'cooling_stage_2': {'pv': 'inactive'}, 'cooling_stage_3': {'pv': 'inactive'}, 'cooling_stage_4': {'pv': 'inactive'}}}
read_success
Traceback (most recent call last):
  File "C:\Users\Desktop\rtuTest.py", line 47, in <module>
    for k,v in data.items():
AttributeError: 'str' object has no attribute 'items'
>>> 

任何小费都很感激..。

EN

回答 1

Stack Overflow用户

发布于 2022-06-26 15:32:33

代码语言:javascript
复制
x = {'status': 'read_success',
     'data': {'cooling_stage_1': {'pv': 'active'},
              'cooling_stage_2': {'pv': 'active'},
              'cooling_stage_3': {'pv': 'inactive'},
              'cooling_stage_4': {'pv': 'inactive'}
              }
     }




temporary_counter = 0


for stuff in x['data'].values():    
    for clg_cmd in stuff.values():
        if clg_cmd == 'active':
            temporary_counter += 1

print(temporary_counter)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72761875

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档