Introduction
In this lab, we will be exploring how to check if a provided string is valid JSON using JavaScript. We will be using the JSON.parse() method along with a try...catch block to determine the validity of the provided string. This lab will help you to better understand how to work with JSON data in JavaScript.
Check If A String Is Valid JSON
To check if a given string is valid JSON, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
JSON.parse()method and atry...catchblock to check if the provided string is valid JSON. - If the string is valid, return
true. Otherwise, returnfalse.
Here's an example code snippet that implements this logic:
const isValidJSON = (str) => {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
};
You can test this function with different input strings, like this:
isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(null); // false
In the last example, null is not a valid JSON string, so the function returns false.
Summary
Congratulations! You have completed the String Is Valid JSON lab. You can practice more labs in LabEx to improve your skills.