I have a simple AJAX call, and the server will return either a JSON string with useful data or an error message string produced by the PHP function mysql_error()
. How can I test whether this data is a JSON string or the error message.
It would be nice to use a function called isJSON
just like you can use the function instanceof
to test if something is an Array.
This is what I want:
if (isJSON(data)){
//do some data stuff
}else{
//report the error
alert(data);
}
Use JSON.parse
function isJson(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}