javascript - Hue api id 识别
问题描述
我正在通过javascript制作我自己的飞利浦色调控制器。我正在尝试识别组和轻 ID。但我不知道如何获得组或灯光的 JSON id。
我得到一个 JSON 格式的 http 答案,如下所示:
{
"1": {
"name": "Woonkamer",
"lights": [
"2",
"1",
"4"
],
"sensors": [],
"type": "Room",
"state": {
"all_on": true,
"any_on": true
},
"recycle": false,
"class": "Living room",
"action": {
"on": true,
"bri": 144,
"hue": 12057,
"sat": 143,
"effect": "none",
"xy": [
0.502,
0.4204
],
"ct": 447,
"alert": "select",
"colormode": "xy"
}
},
"2": {
"name": "keuken",
"lights": [
"3"
],
"sensors": [],
"type": "Room",
"state": {
"all_on": true,
"any_on": true
},
"recycle": false,
"class": "Kitchen",
"action": {
"on": true,
"bri": 254,
"ct": 366,
"alert": "select",
"colormode": "ct"
}
},
例如,我访问类型和名称没有问题,但我不知道如何访问在每个部分开头编写的 id。我不能只得到第一个索引,因为那样我只会得到其他对象,如名称等。
我当前的功能看起来像这样,我可以访问房间名称,但我还需要房间 ID。请记住,这段代码看起来很糟糕,因为我对 JS 很陌生
function getGroups()
{
var url = "https://"+ipadress+"/api/"+username+"/groups";
request.open("GET", url);
request.setRequestHeader("Content-Type", "application/json");
request.send();
request.onreadystatechange = () => {
if (request.readyState === XMLHttpRequest.DONE) {
const res = JSON.parse(request.responseText);
for(var i = 1; i < Object.keys(res).length; i++)
{
if(res[i] != null)
{
if(res[i].type == "Room")
{
var name = res[i].name;
document.getElementById("light_container").style.display = "block";
var onoff = document.createElement('input');
onoff.setAttribute('type', 'button');
onoff.setAttribute('id', name);
onoff.setAttribute('value', name); //need to change this to dynamic function that reads the hue
onoff.setAttribute('onclick', 'changeState("/groups/'+name+'/action")') //need to make change state function
document.body.appendChild(onoff);
}
}
}
};
}
}
解决方案
您在 API 响应中拥有的是一个对象。现在你只能访问它的值,而不是它的键。您可以更改 for 循环的工作方式,改为使用对象键作为索引。然后i
将是您要查找的房间 ID。
for (var i in res) {
.... // everything inside the for loop can stay the same
// but now "i" is the room id you are looking for.
}
推荐阅读
- elasticsearch - 弹性搜索首选项设置自定义值(Java api)
- r - 需要帮助为 summary_table(dplyr::group_by 编写函数
- javascript - 未捕获的类型错误:无法读取 null 的属性“textContent”
- r - tidyverse 中带有索引参数的 by() 等价物是什么?
- python - 我将如何循环一个 python 文件以无限期地打开另一个 python 文件?
- c# - Blazor 组件需要修改父组件的值
- pandas - Pandas:使用 DatetimeIndex 将时间序列列转换为多索引
- reactjs - 使用模板使用数据响应表单获取填充 Datatable 列
- python - 在 python 中加载和调整多个 STL 文件
- c - CS50 凯撒在非数字输入后不退出