python-3.x - 需要帮助清理通过嵌套 JSON 进行的迭代
问题描述
我正在遍历 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
谢谢您的帮助!@纳文
固定的:
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)
解决方案
推荐阅读
- javascript - 我用于替换 url 的 jsfiddle 正在工作,但不在博客源中
- git - 推送到远程后如何将一个分支的更改合并到另一个分支
- python - pandas中如何将重复的数据行收集到单行中?
- machine-learning - 目标标签仅包含允许标签的子集时的 F1 分数计算
- reactjs - history.push() 更改了 url,但在记录 window.location.href 时,这些更改不会反映
- c# - 检测用户何时离开(即关闭浏览器)
- docker - 无法在第二个对等点上部署 fabcar 链代码
- sql - 如何使用 postgis 查询获取分组几何的 bbox?
- vue.js - 如何在 NuxtJS axios 中为 API 使用 env var?
- django - 我的更改密码表单错误在我的 html 页面中不起作用