Reputation: 335
I need to get the name of a JSON element as a value in Javascript.
My Json looks like that:
{
"1": {
"state": {
"on": true,
"bri": 144,
[...]
}
}
I need to get the "1" as a value, as it is the ID of a device and can change.
I tried several things, but
var jsonResponse = JSON.parse(requestId.responseText);
console.log(jsonResponse);
gets me the whole Json object. And
var jsonResponse = JSON.parse(requestId.responseText);
console.log(jsonResponse[i]);
get an undefined.
Some advice would be appreciated.
Upvotes: 0
Views: 31
Reputation: 171679
You have to iterate the object in order to access unknown keys
for( var key in jsonResponse){
console.log(key)
}
// OR
Object.keys(jsonResponse).forEach(key =>{
console.log(key)
})
If you know there is only one key can do:
var key = Object.keys(jsonResponse)[0],
state = jsonResponse[key].state;
console.log(state.bri);
Upvotes: 2