Explain Codes LogoExplain Codes Logo

How to check if a string is a valid JSON string?

javascript
json-validation
error-handling
data-structure
Anton ShumikhinbyAnton Shumikhin·Aug 16, 2024
TLDR

To check if a string is valid JSON in JavaScript, simply wrap a call to JSON.parse() inside a try..catch block. A successful parse returns true; an exception triggers the catch block to return false.

const isValidJSON = str => { try { JSON.parse(str); // No news is good news! return true; } catch (e) { // Seems like they've got me sussed! return false; } }; // Usage: console.log(isValidJSON('{"valid": true}')); // true lightsaber, ready to fight! console.log(isValidJSON('Invalid JSON')); // false, droid found. Abort!

Options and pitfalls of validation

The standard method with try..catch is certainly good, but at times you might need to validate JSON avoiding exceptions. Here's how:

Function without exceptions:

function isJSONWithoutExceptions(str) { if (/^[\],:{}\s]*$/.test(str .replace(/\\["\\\/bfnrtu]/g, '@') // Waving magic wand here .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // More fairy dust return true; // Magic worked! } return false; // Cinders again! }

The regular expression in this code verifies the structure of the given string corresponds to JSON.

Checking parsed output:

This method involves parsing the string and checking the result type. Only objects and arrays represent valid JSON in JavaScript.

const isValidJSONStructure = str => { try { const result = JSON.parse(str); return (result && typeof result === 'object' && result !== null); // Everything is object in JS! } catch (e) { return false; // Who's sending trash again? } };

Catering to the specifics of JSON structure

Confirming an array of objects:

const isValidArrayOfObjects = str => { try { const jsonArray = JSON.parse(str); return Array.isArray(jsonArray) && jsonArray.every(item => typeof item === 'object' && item !== null); // Raiders of the Lost Array } catch (e) { return false; // Got lost in array! } };

Above method is a double whammy. First, it checks if parsed JSON creates an array and for each object in the array, verifies if it is an object, matching our specific requirement.

Debugging scenarios in real world

At times, your debugger settings might lead to trouble with try..catch blocks. Or you're one avoiding them in general. Fret not, alternatives exist.

Replace method approach:

const isValidJSONAdvanced = str => { let replacedStr = str.replace(/[\\]/g, '@'); // Hi John Wick! No kill please. if (/^[\],:{}\s]*$/.test(replacedStr)) { // Your additional checks here return true; // Plain sailing! } return false; // Red alert! };