How to test if a string is JSON or not?

222

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

This question is tagged with javascript mysql json

~ Asked on 2012-03-21 12:38:58

The Best Answer is


373

Use JSON.parse

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

~ Answered on 2012-03-21 12:42:26


96

This code is JSON.parse(1234) or JSON.parse(0) or JSON.parse(false) or JSON.parse(null) all will return true.

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

So I rewrote code in this way:

function isJson(item) {
    item = typeof item !== "string"
        ? JSON.stringify(item)
        : item;

    try {
        item = JSON.parse(item);
    } catch (e) {
        return false;
    }

    if (typeof item === "object" && item !== null) {
        return true;
    }

    return false;
}

Testing result:

isJson test result

~ Answered on 2015-10-27 13:56:02


Most Viewed Questions: