How to use JSON.parse() method In Javascript
The JSON.parse() method in JavaScript is used to parse a JSON string which is written in a JSON format and returns a JavaScript object.
Syntax:
JSON.parse( text, function);
Example 1: This example checks the validity of JSON string by the JSON.parse() method by creating a function.
// Input sting
let str = '{ "prop_1": "val_1", "prop_2": "val_2" }';
console.log("Input string is : " + str);
// Function to test string
function testJSON(text) {
if (typeof text !== "string") {
return false;
}
try {
JSON.parse(text);
return true;
} catch (error) {
return false;
}
}
// Function to display output
function gfg_Run() {
console.log(testJSON(str));
}
// Function call
gfg_Run();
Output
Input string is : { "prop_1": "val_1", "prop_2": "val_2" } true
Example 2: This example is returning false because the property value val_1 is not a string.
// 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 {
return JSON.parse(str) && !!str;
} 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" } false
Example 3: This example is returning true by using the JSON.parse() method along with typechecking of the text.
// Input sting
let str = '{ "prop_1": 1, "prop_2": "val_2" }';
console.log("Input string is : " + str);
// Function to test string
function isJSON(str) {
try {
return JSON.parse(str) && !!str;
} 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": 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