Reputation: 962
I am looking for direct way of checking if the JSON I recieve from my backend holds the value i need without throwing an exception or making a for loop of if
-statements.
I would like it to look something like this:
success = function(requestBody, xhr, options){
jsonObj = JSON.parse(requestBody);
if (!json.path.to.item.is.very.deep[0].really[3]){
responseErrorHandler(requestBody, xhr, options)
}
// More Code here
}
This code obviously does not work because if I.E. the json object does not have the item
object and error is throw and the code stops.
I can make a for
-loop and parse the json but i like to see a shortcut.
Upvotes: 0
Views: 79
Reputation: 72271
An error is thrown - it's a good thing, you can handle it! Wrap the attempt to access the value (and only that line, to avoid catching unrelated errors) in try-catch, for example:
try {
var x = json.path.to.item.is.very.deep[0].really[3];
} catch(e) {
// ... handle failure...
return;
}
if (typeof x !== "number") { // or whatever you need
// ... handle failure...
return;
}
// handle success
Upvotes: 1