Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check if null from json

Im using the following javascript. it writes fine until it gets to a result which doesn't have a value. in console log it shows this

Uncaught TypeError: Cannot read property 'text' of null

but my script below doesn't seem to work

            var checkCaption = photo.caption.text;
            if (checkCaption == null) {
                caption = 'meh';
            } else {
                caption = photo.caption.text;
            }
like image 251
ngplayground Avatar asked Oct 07 '12 16:10

ngplayground


3 Answers

In your example, photo.caption is null, so your code breaks on the photo.caption.text call, before the check is done.

var caption;

if(photo.caption != null) { // Covers 'undefined' as well
  caption = photo.caption.text;
} else {
  caption = "meh";
}
like image 171
Renato Zannon Avatar answered Nov 14 '22 20:11

Renato Zannon


In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:

 if (JSON.stringify(response.data)=='{}') {
      //the response is null
 }
 else {
      //the response of JSON is not null
 }

It works fine for me to check if the response is null or not.

like image 43
Ebrahim Avatar answered Nov 14 '22 20:11

Ebrahim


For me the check of length of the json object resolved the issue -

   if Object.keys(jsonobj).length == 0){
     // JSON object is null
    }
   else {
     // JSON object has data 
    }
like image 1
devman Avatar answered Nov 14 '22 22:11

devman