How to parse a string and create JSON object

JSON Object

The JSON object has two methods: stringify() and parse().

stringify() methods serialize JavaScript objects into a JSON string. parse() parses JSON into a native JavaScript value


<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var book = { 
            title: "JavaScript",
            authors: ["J" ], 
            edition: 3, <!--   w  w w .  j ava 2  s.  co m-->
            year: 2011
        }; 
        
        var jsonText = JSON.stringify(book); 
        document.writeln(jsonText);

    </script>

</head>
<body>
  
</body>
</html>

Click to view the demo

JSON.parse()

A JSON string can be passed directly into JSON.parse() and it creates an appropriate JavaScript value.


<!DOCTYPE html>
<html>
<head>
    <title>Operator Example</title>
    <script type="text/javascript">
        var book = { 
            title: "JavaScript",
            authors: ["J" ], 
            edition: 3, <!-- www .jav  a2  s.com-->
            year: 2011
        }; 
        
        var jsonText = JSON.stringify(book); 
        document.writeln(jsonText);
        var bookCopy = JSON.parse(jsonText); 
        document.writeln(bookCopy);
    </script>

</head>
<body>
  
</body>
</html>

Click to view the demo

An error is thrown if the text passed into JSON.parse() is not valid JSON.

Parsing Options

The JSON.parse() method accepts a function that is called on each key-value pair.

The function receives two arguments, the key and the value, and needs to return a value.

If the function returns undefined, then the key is removed from the result; if it returns any other value, that value is inserted into the result.

A very common use of the receiver function is to turn date strings into Date objects. For example:


<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        var book = { 
            "title": "JavaScript",
            "authors": ["J"], 
            edition: 3, <!-- w  w w .j av a2s  .c om-->
            year: 2011, 
            releaseDate: new Date(2011, 11, 1) 
        }; 
        
        var jsonText = JSON.stringify(book); 
        
        var bookCopy = JSON.parse(jsonText, function(key, value){ 
                if (key == "releaseDate"){ 
                    return new Date(value); 
                } else { 
                    return value; 
                } 
        }); 
        
        document.writeln(bookCopy.releaseDate.getFullYear()); 
    </script>

</head>
<body>
  
</body>
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions