循环通过API JSON数据和计数状态'
我正在从一个函数上的请求库中获取REST API的数据:
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看起来像这样:
{'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> Active <的冷却阶段/代码>?在
数据中
可能有很多阶段,但是在此示例中,只有4个,coloring_stage_1
通过COOLING_STAGE_4
。希望这是有道理的!
如果我调用功能并尝试循环遍历它:
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)
此错误:
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'
>>>
任何提示都赞赏...
I am getting data from a rest API with the requests library on a function:
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()
Where x looks like this:
{'status': 'read_success', 'data': {'cooling_stage_1': {'pv': 'active'}, 'cooling_stage_2': {'pv': 'active'}, 'cooling_stage_3': {'pv': 'inactive'}, 'cooling_stage_4': {'pv': 'inactive'}}}
How do I loop through the data
and count all of the cooling stages that are active
? In data
there could be many stages but in this example there is only 4, cooling_stage_1
through cooling_stage_4
. Hopefully this makes sense!
If I call the function and attempt to loop through it:
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)
This errors out:
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'
>>>
Any tips appreciated...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)