我正在遍历JSON内容。我返回的是传感器名称+温度。 value
下有两个capability
键。我在想出忽略第二个逻辑的简单逻辑时遇到了麻烦。我是python的新手,但感觉这是一个简单的调整。我似乎找不到一个很好的例子说明如何忽略第二个值的拉动。
数据:
"remoteSensors": [
{
"id": "rs:100",
"name": "Guest Bedroom",
"type": "ecobee3_remote_sensor",
"code": "TPCM",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "690"
},
{
"id": "2",
"type": "occupancy",
"value": "false"
}
]
},
{
"id": "rs:101",
"name": "Mudd Room",
"type": "ecobee3_remote_sensor",
"code": "X9YF",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "572"
},
{
"id": "2",
"type": "occupancy",
"value": "false"
}
]
},
{
"id": "rs:102",
"name": "Master Bedroom",
"type": "ecobee3_remote_sensor",
"code": "YDNZ",
"inUse": false,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "694"
},
{
"id": "2",
"type": "occupancy",
"value": "true"
}
]
},
{
"id": "ei:0",
"name": "Main Floor",
"type": "thermostat",
"inUse": true,
"capability": [
{
"id": "1",
"type": "temperature",
"value": "725"
},
{
"id": "2",
"type": "humidity",
"value": "37"
},
{
"id": "3",
"type": "occupancy",
"value": "false"
}
]
}
]
代码:
import requests
import json
url = 'https://api.ecobee.com/1/thermostat'
header = {'Content-Type': 'application/json;charset=UTF-8',
'Authorization': 'Bearer ZkEf7ONibogGpMQibem3SlhXhEOS99zK'}
params = {'json': ('{"selection":{"selectionType":"registered",'
'"includeRuntime":"true",'
'"includeSensors":"true",'
'"includeProgram":"true",'
'"includeEquipmentStatus":"true",'
'"includeEvents":"true",'
'"includeWeather":"true",'
'"includeSettings":"true"}}')}
request = requests.get(url, headers=header, params=params)
#print(request)
thermostats = request.json()['thermostatList']
remote_sensors = thermostats[0]['remoteSensors']
for eachsensor in thermostats[0]['remoteSensors']:
for temp in eachsensor['capability']:
name = eachsensor.get('name')
temp = temp.get('value')
print(name, temp)
实际结果:
Guest Bedroom 690
Guest Bedroom false
Mudd Room 579
Mudd Room false
Master Bedroom 698
Master Bedroom false
Main Floor 731
Main Floor false
预期结果:
Guest Bedroom 690
Mudd Room 579
Master Bedroom 698
Main Floor 731
感谢您的帮助! @Naveen
已修复:
for eachsensor in thermostats[0]['remoteSensors']:
for temp in eachsensor['capability']:
name = eachsensor.get('name')
tempr = temp.get('value')
id = temp.get('id')
if id == '1':
print(name, tempr, id)