JSON未捕获类型错误

时间:2015-01-07 18:23:15

标签: javascript json

我正在使用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;
    }
  }
}

2 个答案:

答案 0 :(得分:2)

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

添加pictures[p].caption &&以评估内部caption中的if

这对您有用(请注意,我也合并了您的两个if,我只在一个if中进行了所有评估):

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

答案 1 :(得分:0)

你可以尝试一下:

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

因为标题属性始终在此处,但如果不可用则可能为null

相关问题