How to test if a string is JSON or not?

Sometimes we need to save json in our relational database. As backend engineer we need to validate the string is JSON well-formed. Otherwise, when we parse the value, our app will crash.

This is the solution “How to test if a string is JSON or not?” with very simple function

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

Leave a Comment