Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery check if json var exist

How can I with jquery check to see if a key/value exist in the resulting json after a getJSON?

function myPush(){
    $.getJSON("client.php?action=listen",function(d){
        d.chat_msg = d.chat_msg.replace(/\\\"/g, "\"");
        $('#display').prepend(d.chat_msg+'<br />');
        if(d.failed != 'true'){ myPush(); }
    });
}

Basically I need a way to see if d.failed exist and if it = 'true' then do not continue looping pushes.

like image 222
David Avatar asked Dec 16 '22 13:12

David


2 Answers

You don't need jQuery for this, just JavaScript. You can do it a few ways:

  • typeof d.failed- returns the type ('undefined', 'Number', etc)
  • d.hasOwnProperty('failed')- just in case it's inherited
  • 'failed' in d- check if it was ever set (even to undefined)

You can also do a check on d.failed: if (d.failed), but this will return false if d.failed is undefined, null, false, or zero. To keep it simple, why not do if (d.failed === 'true')? Why check if it exists? If it's true, just return or set some kind of boolean.

Reference:

http://www.nczonline.net/blog/2010/07/27/determining-if-an-object-property-exists/

like image 177
beatgammit Avatar answered Dec 24 '22 14:12

beatgammit


Found this yesterday. CSS like selectors for JSON

http://jsonselect.org/

like image 27
dexter Avatar answered Dec 24 '22 15:12

dexter