最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript check if null from json - Stack Overflow

programmeradmin1浏览0评论

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

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;
            }
Share Improve this question asked Oct 7, 2012 at 16:02 ngplaygroundngplayground 21.6k37 gold badges98 silver badges174 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 21

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";
}

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.

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 
    }

I know it's pretty late but it might help someone else. you can do this in one line

var checkCaption = photo.caption?.text ?? 'meh';

You can also use

   if ("caption" in photo) {
    caption = photo.caption?.text
   } else {
    caption = "meh"
   }
发布评论

评论列表(0)

  1. 暂无评论