Hi Friends đź‘‹,
Welcome To Infinitbility! ❤️
Today, I’m going to show you how do I check if a string is a valid JSON string in javascript, here we will use the JSON.parse()
method to validate string is a JSON string or not.
The JSON.parse()
method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.
Let’s start today’s tutorial How to check if a string is a valid JSON string in javascript?
Before going to code, let’s understand what we are going to do?
- Create a function that validates JSON string
- Use
Date.parse()
on in created function with try/catch ( without try/catch hard handle errors show every time when we validate JSON string we should use try/catch block ) - Create two JSON string variables one is a valid JSON string and the second is an invalid string
- Use created a function to validate
- Console which string is a valid
1// Create a function which validate json string2function IsJsonString(str) {3 // Use `Date.parse()` on in created function with try/catch4 try {5 JSON.parse(str);6 } catch (e) {7 return false;8 }9 return true;10}1112// Create two json string variables one is a valid json string and the second is a invalid string13let firstJsonStr = '{"name":"infinitbility","domain":"infinitbility.com","age":2}';14let secondJsonStr = '{nam:infinitbilit,domain:infinitbility.com,age:2}';1516// Use created function to validate17// Console which string is a valid18if(IsJsonString(firstJsonStr)){19 console.log("firstJsonStr is a valid")20}2122if(IsJsonString(secondJsonStr)){23 console.log("secondJsonStr is a valid")24}
When running the above program it should console 'firstJsonStr is a valid'
in the log. let’s check the output.

I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.