Open In App

JavaScript JSON parse() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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


Last Updated : 02 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads