繁体   English   中英

JSON未捕获类型错误

[英]JSON Uncaught Type Error

我正在使用instagram API,如果标题不存在或没有文本,则根本不包含该节点。 因此,我进行了一项检查,以查看是否存在可以使用标题的标题,但是如果标题存在并且子节点文本不存在,则出现错误: Uncaught TypeError: Cannot read property 'text' of null

这是我的代码:

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

显然, caption属性存在,但在某些情况下似乎为null ,并且当您评估(null).text ,您将得到问题中详细说明的错误。

添加pictures[p].caption &&来评估if caption

这应该为您工作(请注意,我还将您的两个if合并,并且仅对if进行了所有评估):

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

您可以尝试:

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

代替

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

因为caption属性始终在此处,但如果不可用,则可以为null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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