Open In App
Related Articles

JavaScript JSON parse() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

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( string, function )

Parameters: This method accepts two parameters as mentioned above and described below:

  • string: It is a required parameter and it contains a string that is written in JSON format.
  • function: It is an optional parameter and is used to transform results. The function called for each item.

Return Value: This method returns an object corresponding to the given JSON text.

Example 1: Below is an example of the JSON parse() Method.

JavaScript




let obj = JSON.parse('{"var1":"Geeks","var2":"forGeeks!"}');
 
console.log(obj.var1 + " " + obj.var2);


Output:

GeeksforGeeks!

Example 2: This example parses a string and returns the JavaScript object. 

Javascript




let obj = JSON.parse('{"var1":"Hello","var2":"Geeks!"}');
 
console.log(obj.var1 + " " + obj.var2);


Output

Hello Geeks!

Example 3: This example uses the reviver function to parse a string and return the JavaScript object. 

Javascript




let text = '{ "var1":"Amanda", "gender":"male"}';
 
let obj = JSON.parse(text, function (key, value) {
    if (value == "male") {
        return ("female");
    } else {
        return value;
    }
});
console.log(obj.var1 + ", " + obj.gender);


Output

Amanda, female

We have a complete list of Javascript JSON methods, to check those please go through Javascript JSON Complete Reference article.

Supported browsers:

  • Chrome 4.0
  • Firefox 3.5
  • Opera 11.0
  • Internet Explorer 8.0
  • Safari 4.0

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials