HomeLanguagesJavascriptJavaScript JSON parse() Method

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:

  • 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:

neveropen!

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
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS