Javascript – How to check if a string is a valid JSON string in JavaScript without using Try/Catch

javascriptjson

Something like:

var jsonString = '{ "Id": 1, "Name": "Coke" }';

//should be true
IsJsonString(jsonString);

//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")

The solution should not contain try/catch. Some of us turn on "break on all errors" and they don't like the debugger breaking on those invalid JSON strings.

Best Answer

Use a JSON parser like JSON.parse:

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