[英]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. 我正在使用instagram API,如果标题不存在或没有文本,则根本不包含该节点。 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
. 因此,我进行了一项检查,以查看是否存在可以使用标题的标题,但是如果标题存在并且子节点文本不存在,则出现错误: 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. 显然, caption
属性存在,但在某些情况下似乎为null
,并且当您评估(null).text
,您将得到问题中详细说明的错误。
Add pictures[p].caption &&
to evaluate for caption
in your inner if
. 添加pictures[p].caption &&
来评估if
caption
。
This should work for you (note that I also merge your two if
s and I did all evaluations in only one 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;
}
}
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 因为caption属性始终在此处,但如果不可用,则可以为null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.