Javascript javascript检查json是否为null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12770393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript check if null from json
提问by ngplayground
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
我使用以下 javascript。它写得很好,直到它得到一个没有值的结果。在控制台日志中它显示了这一点
Uncaught TypeError: Cannot read property 'text' of null
未捕获的类型错误:无法读取 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;
}
回答by Renato Zannon
In your example, photo.caption
is null, so your code breaks on the photo.caption.text
call, before the check is done.
在您的示例中,photo.caption
为 null,因此photo.caption.text
在检查完成之前,您的代码会在调用时中断。
var caption;
if(photo.caption != null) { // Covers 'undefined' as well
caption = photo.caption.text;
} else {
caption = "meh";
}
回答by Ebrahim
In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:
就我而言,我使用 JSON.stringify 来检查我是否收到了来自 REST 服务器的 {}(空)响应:
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.
检查响应是否为空对我来说很好用。
回答by devman
For me the check of length of the json object resolved the issue -
对我来说,检查 json 对象的长度解决了这个问题 -
if Object.keys(jsonobj).length === 0){
// JSON object is null
}
else {
// JSON object has data
}