'javascript check if null from json
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
Uncaught TypeError: Cannot read property 'text' of 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;
}
Solution 1:[1]
In your example, photo.caption is null, so your code breaks on the photo.caption.text call, before the check is done.
var caption;
if(photo.caption != null) { // Covers 'undefined' as well
caption = photo.caption.text;
} else {
caption = "meh";
}
Solution 2:[2]
In my case i use the JSON.stringify to check I have received {} (null) response from the REST server:
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.
Solution 3:[3]
For me the check of length of the json object resolved the issue -
if Object.keys(jsonobj).length == 0){
// JSON object is null
}
else {
// JSON object has data
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Renato Zannon |
| Solution 2 | Ebrahim |
| Solution 3 | MBT |
