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;
}
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";
}
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With