isJsonString('{ "Id": 1, "Name": "Coke" }')

should be true and

isJsonString('foo')
isJsonString('<div>foo</div>')

should be false.

I’m looking for a solution that doesn’t use try/catch because I have my debugger set to “break on all errors” and that causes it to break on invalid JSON strings.

25 s
25

Use a JSON parser like JSON.parse:

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

Leave a Reply

Your email address will not be published. Required fields are marked *