jeffery_the_wind jeffery_the_wind - 7 months ago 18
SQL Question

How to test if a string is JSON or not?

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);
}

Answer

Use JSON.parse

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}