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?

  1. Create a function that validates JSON string
  2. 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 )
  3. Create two JSON string variables one is a valid JSON string and the second is an invalid string
  4. Use created a function to validate
  5. Console which string is a valid
// Create a function which validate json string
function IsJsonString(str) {
  	// Use `Date.parse()` on in created function with try/catch
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

// Create two json string variables one is a valid json string and the second is a invalid string
let firstJsonStr = '{"name":"infinitbility","domain":"infinitbility.com","age":2}';
let secondJsonStr = '{nam:infinitbilit,domain:infinitbility.com,age:2}';

// Use created function to validate
// Console which string is a valid
if(IsJsonString(firstJsonStr)){
 console.log("firstJsonStr is a valid") 
}

if(IsJsonString(secondJsonStr)){
 console.log("secondJsonStr is a valid") 
}

When running the above program it should console 'firstJsonStr is a valid' in the log. let’s check the output.

javascript, check if a string is a valid json string example
javascript, check if a string is a valid json string example

I hope it’s help you, All the best 👍.