【发布时间】:2021-05-18 21:48:00
【问题描述】:
我正在通过 JavaScript 制作我自己的飞利浦 Hue 控制器。我正在尝试识别组和轻 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);
}
}
}
};
}
}
【问题讨论】:
标签: javascript json api