Open In App

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

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

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



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




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. 




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. 




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:


Article Tags :