The Wayback Machine - https://web.archive.org/web/20240619231046/https://www.geeksforgeeks.org/javascript-check-if-a-string-is-a-valid-json-string/
Open In App

Check if a string is a valid JSON string using JavaScript

Last Updated : 30 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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();

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. 

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();

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. 

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();

Output
Input 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();

Output
Input 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();

Output
Input string is : { "prop_1": "val_1", "prop_2": "val_2" }
true




Similar Reads

How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below: Approach 1: Using JSON.parse() MethodThe basic method to convert JSON String to Array of JSON object
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
JavaScript Program to Check Valid Parentheses Using String
In this article, we will learn how we can check valid parentheses of a string, and write a program to check whether the pairs and order of "{ ", " } ", "(", ")", "[", "]" in the string expression is right or not. Example: Input: exp = "[()][()()]()" Output: True.Explanation: all of the brackets are properly formed.Input: exp = "[(])"Output: FalseEx
5 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
How to check a date is valid or not using JavaScript ?
To check if a date is valid or not in JavaScript, we have to know all the valid formats of the date for e.g."YYYY/DD/MM","DD/MM/YYYY", and "YYYY-MM-DD", etc. we will have a given date format and we need to check whether that given format is valid or not according to the official and acceptable date format. There are two methods to solve this proble
4 min read
JavaScript Check if a string is a valid hex color representation
Given a hex color code and the task is to check whether the given hexCode is valid or not using JavaScript. We are going to discuss a few techniques. Approach: Valid hexcode contains the alphabets(A-F) and integers(0-9) and is of length 3 or 6.A RegExp is used to check whether the alphabets ranging between A and F, Integers from 0-9, and is of leng
1 min read
How to Check if a String Contains a Valid URL Format in JavaScript ?
A string containing a valid URL format adheres to standard conventions, comprising a scheme (e.g., "http://" or "https://"), domain, and optionally, a path, query parameters, and fragments. Ensuring this format is crucial for data consistency and accurate handling of URLs in applications. There are several methods that can be used to check if a str
2 min read
How to check if a string is a valid IP address format in JavaScript ?
In this article, we will see how to check if a string is a valid IP address or not. An IP address is a unique identifier assigned to each device connected to a computer network that uses the Internet Protocol for communication. There are two common formats for IP addresses: IPv4 and IPv6. Checking if a string is a valid IP address format in JavaScr
3 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read