DaPole DaPole - 8 months ago 37
Javascript Question

getting value of JSON-name

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);

gets me the whole Json object. And

var jsonResponse = JSON.parse(requestId.responseText);

get an undefined.

Some advice would be appreciated.

Answer Source

You have to iterate the object in order to access unknown keys

for( var key in jsonResponse){
// OR    
Object.keys(jsonResponse).forEach(key =>{

If you know there is only one key can do:

var key =  Object.keys(jsonResponse)[0],
    state = jsonResponse[key].state;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download