How to use Regular Expression In Javascript
Regular expressions can also be used to validate JSON strings.
This regular expression checks if the given string conforms to the syntax of a JSON string by matching the basic structure and escaping rules of JSON strings. If the string passes the regex test, it returns true; otherwise, it returns false.
Example:
// Input string
let str = '{ "prop_1": "val_1", "prop_2": "val_2" }';
console.log("Input string is : " + str);
// Function to test string
function isJSON(str) {
const jsonRegex = /^[\],:{}\s]*$/
.test(str.replace(/\\["\\\/bfnrtu]/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''));
return jsonRegex;
}
// Function to display output
function gfg_Run() {
console.log(isJSON(str));
}
// Function call
gfg_Run();
Output
Input string is : { "prop_1": "val_1", "prop_2": "val_2" } true
Check if a string is a valid JSON string using JavaScript
We will be given a string and we need to validate whether the given string is a valid JSON string or not. JSON string is the same as a javaScript object and it must follow the syntax of that object. If the syntax is correct then we have to return true or we have to return false.
Methods to Check if a String is Valid JSON String:
Table of Content
- Method 1: Using JSON.parse() method
- Method 2: Using JSON.stringify() method
- Method 3: Using Lodash _.isJSON() Method
- Method 4: Using Regular Expression