user3885139
user3885139

Reputation: 11

javascript check if JSON key exists and display the value

I've been tinkering with Z-Wave lately and I'm trying to make a page to include/exclude their products. But it's not going too well. I'm trying to check if a JSON key exists then display it on the page. I get

TypeError: data.controller is undefined

Here is the code:

window.setInterval(function(){
   getData();
}, 2000);

function getData()
{
var milliseconds = (new Date).getTime();
var time = milliseconds.toString().substr(0, milliseconds.toString().length - 3) ;

$.postJSON( "http://192.168.1.102:8083/ZWaveAPI/Data/" + time, function( data ) {
    if(data.controller.lastExcludedDevice.value) alert("EXCLUDED SOMETHING");
    if(data.controller.lastIncludedDevice.value) alert("INCLUDED SOMETHING");
});   
}

$.postJSON = function(url, data, callback, sync) {

// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
    sync = sync || callback;
    callback = data;
    data = {};
};
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    success: callback,
    error: callback,
    async: (sync!=true)
});
};

Json:

{
  "controller.data.controllerState": {
    "value": 0,
    "type": "int",
    "invalidateTime": 1424781697,
    "updateTime": 1425338938
  },
  "controller.data.lastIncludedDevice": {
    "value": 42,
    "type": "int",
    "invalidateTime": 1424781697,
    "updateTime": 1425338938
  },
  ......

Any help is greatly appreciated.

Upvotes: 1

Views: 648

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

if the dots are part of the key you need to use the [] notation.

for example

if (data['controller.data.controllerState'].value) ...

or

if (data['controller.data.lastIncludedDevice'].value) ...

Upvotes: 2

djechlin
djechlin

Reputation: 60768

Try this:

if(data.controller && 
    data.controller.lastExcludedDevice.value) 
    alert("EXCLUDED SOMETHING");

Think of it this way: console.log({}.x) prints "undefined." console.log({}.x.y) throws an error. You're allowed to work with undefined but it throws an error if you try to access properties of it.

Use the short-circuiting property of && to expedite this check:

if(a && a.b && a.b.c && a.b.c.d) {
    console.log("Not an error to print", a.b.c.d);
}{

Upvotes: 0

Related Questions