Validate JSON String in JavaScript

- 1 minute read

Working with JSON strings in JavaScript can be a bit of a pain, because if you try to pass an invalid JSON string to the built-in JSON.parse method, an error will be thrown.

The following custom utility function can simplify the headache by checking whether a given string has valid JSON formatting and can be parsed:

const isJSON = (string) => {
    try {
        JSON.parse(string);
    } catch (e) {
        return false;
    }
    return true;
};

// isJSON(`example`) will return false

// isJSON(`{\"color\":\"red\"}`) will return true

The function accepts one parameter and will return true or false, depending on whether the string can be parsed.

If the string can be parsed, it is safe to parse it outside of a try…catch statement. Here’s an example:

const string = `{\"color\":\"red\"}`;

if (!!isJSON(string)) {
    const json = JSON.parse(string);
} else {
    console.log(`"${string}" cannot be parsed!`);
}

Link to this section Conclusion

Anyway, I’ve found this method much cleaner than littering my code with try…catch statements when trying to parse multiple strings.

I hope you found it useful too!