How to use JSON.stringify() method In Javascript
The JSON.stringify() method in Javascript is used to create a JSON string out of it.
Syntax:
JSON.stringify(value, replacer, space);
Example: In this example, we will try to convert the given object to a string using JSON.stringify() method
// Input sting
let str = '{ "prop_1": "val_1", "prop_2": "val_2" }';
console.log("Input string is : " + str);
// Function to test string
function isJSON(str) {
try {
JSON.stringify(JSON.parse(str));
return true;
} catch (e) {
return false;
}
}
// 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