Categories
JavaScript Answers

How to Check if a String is JSON in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Check if a String is JSON in JavaScript?”

Ummm… try the value ‘foo’. Or 123. Or ‘123’. Last I checked, neither strings nor numbers are valid JSON notation.

Leave a Reply

Your email address will not be published.