Check if a string is a valid JSON string using JavaScript
Last Updated :
25 Jun, 2024
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:
Method 1: Using JSON.parse() method
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.
JavaScript
// 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();
OutputInput 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.
JavaScript
// 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();
OutputInput 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.
JavaScript
// 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();
OutputInput string is : { "prop_1": 1, "prop_2": "val_2" }
true
Method 2: Using JSON.stringify() method
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
JavaScript
// 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();
OutputInput string is : { "prop_1": "val_1", "prop_2": "val_2" }
true
Method 3: Using Lodash _.isJSON() Method
In Lodash _.isJSON() Method approach, we are using Lodash _.isJSON() method that returns the boolean value that is true if the passes value is a JSON string else it returns false.
Example: In this example, we are using the Lodash _.isJSON() method.
JavaScript
// Defining lodash contrib variable
let _ = require('lodash-contrib');
// Checking for _.isJSON() method
console.log("The Value is JSON : " +_.isJSON(
'{"GeeksforGeeks" : "A Computer Science portal for Geeks"}'));
Output:
The Value is JSON : true
Method 4: Using Regular Expression
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:
JavaScript
// 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();
OutputInput string is : { "prop_1": "val_1", "prop_2": "val_2" }
true
Method 5: Using Try-Catch Block
Using a try-catch block in JavaScript is a simple and effective way to validate if a string is a valid JSON. By attempting to parse the string with JSON.parse(), any syntax errors will be caught by the catch block, allowing us to determine if the string is valid JSON or not.
Example:
JavaScript
function isValidJSON(str) {
try {
JSON.parse(str);
return true;
} catch (e) {
return false;
}
}
// Example usage:
const jsonString1 = '{"name":"John", "age":30, "city":"New York"}';
const jsonString2 = '{"name":"John", "age":30, "city":"New York"';
console.log(isValidJSON(jsonString1)); // Output: true
console.log(isValidJSON(jsonString2)); // Output: false
Method 6: Using a Custom Validation Function
A custom validation function can be implemented to manually check if a string is a valid JSON. This function will ensure the string starts and ends with appropriate JSON delimiters and contains valid JSON structure within.
Example:
JavaScript
function isCustomValidJSON(str) {
// Check if the string starts with '{' or '[' and ends with '}' or ']'
if ((str.startsWith('{') && str.endsWith('}')) ||
(str.startsWith('[') && str.endsWith(']'))) {
try {
// Attempt to parse the string to verify JSON structure
const parsed = JSON.parse(str);
// Additional checks to ensure the parsed result is an object or array
if (typeof parsed === 'object' && parsed !== null) {
return true;
}
} catch (e) {
return false;
}
}
return false;
}
const jsonString1 = '{"name":"John", "age":30, "city":"New York"}';
const jsonString2 = '{"name":"John", "age":30, "city":"New York"';
const jsonString3 = '[1, 2, 3, 4]';
const jsonString4 = '[1, 2, 3, 4';
console.log(isCustomValidJSON(jsonString1)); // Output: true
console.log(isCustomValidJSON(jsonString2)); // Output: false
console.log(isCustomValidJSON(jsonString3)); // Output: true
console.log(isCustomValidJSON(jsonString4)); // Output: false
Outputtrue
false
true
false
Please Login to comment...