Sometimes, we want to check if a string is JSON in JavaScript.
In this article, we’ll look at how to check if a string is JSON in JavaScript.
Check if a String is JSON in JavaScript
To check if a string is JSON in JavaScript, we can use the JSON.parse
method within a try-catch block.
For instance, we can write:
const jsonStr = JSON.stringify({
foo: 'bar'
})
try {
const json = JSON.parse(jsonStr);
} catch (e) {
console.log('invalid json');
}
to check if jsonStr
is a valid JSON string.
Since we created the JSON string by calling JSON.stringify
with an object, it should be valid JSON.
Next, we have a try-catch block with the JSON.parse
call in the try
block to try to parse the jsonStr
string with JSON.parse
.
Since jsonStr
is a valid JSON string, the code in the catch
block shouldn’t run.
If jsonStr
isn’t a valid JSON string, then the code in the catch
block runs since JSON.parse
will throw an exception if it’s called with an invalid JSON string.
Conclusion
To check if a string is JSON in JavaScript, we can use the JSON.parse
method within a try-catch block.