简体   繁体   中英

JSON Uncaught Type Error

I am using the instagram API and if a caption doesnt exist or doesnt have text it doesnt include the node at all. So I included a check to see if caption exists which works, but if caption exists and the child node text does not, then I get the error: Uncaught TypeError: Cannot read property 'text' of null .

This is my code:

for (p in pictures) {
  if (pictures[p].hasOwnProperty('caption')) {
    if (pictures[p].caption.text != null) {
      captionString = pictures[p].caption.text;
    }
  }
}

Apparently, the caption property exists, but it seems to be null for some cases, and when you evaluate (null).text , you are getting the error detailed in your question.

Add pictures[p].caption && to evaluate for caption in your inner if .

This should work for you (note that I also merge your two if s and I did all evaluations in only one if ):

for(p in pictures) {
  if (pictures[p].hasOwnProperty('caption') && pictures[p].caption && pictures[p].caption.text != null) {
    captionString = pictures[p].caption.text;
  }
}

you could just try :

if(pictures[p].caption != null){
     captionString = pictures[p].caption.text;
}

instead of

if(pictures[p].hasOwnProperty('caption')){
     if(pictures[p].caption.text != null){
          captionString = pictures[p].caption.text;
     }
}

Because the caption property is always here, but may be null if not available

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM