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 return a JavaScript object.

Syntax:

JSON.parse( string, function )

Parameters: It accepts two parameter which are listed below:



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

Example 1: This example parse a string and return the JavaScript object.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript JSON parse() Method
    </title>
</head>
  
<body>
      
    <h1>GeeksforGeeks</h1>
      
    <h2>
        JavaScript JSON parse() Method
    </h2>
      
    <p id="GFG"></p>
      
    <!-- Script to parse a string and return
        JavaScript object -->
    <script>
        var obj = JSON.parse('{"var1":"Hello", "var2":"Geeks!"}');
          
        document.getElementById("GFG").innerHTML
                = obj.var1 + " " + obj.var2;
    </script>
</body>
  
</html>                    

chevron_right


Output:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript JSON parse() Method
    </title>
</head>
  
<body>
      
    <h1>GeeksforGeeks</h1>
      
    <h2>
        JavaScript JSON parse() Method
    </h2>
      
    <p id="GFG"></p>
      
    <!-- Script to parse a string and return
        JavaScript object -->
    <script>
        var text = '{ "var1":"Amanda", "gender":"male"}';
          
        var obj = JSON.parse(text, function (key, value) {
            if (value == "male") {
                return ("female");
            } else {
                return value;
            }
        });
        document.getElementById("GFG").innerHTML
                = obj.var1 + ", " + obj.gender; 
    </script>
</body>
  
</html>                    

chevron_right


Output:

Supported browsers: The browser supported by JavaScript JSON parse() method are listed below:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.