Parsing
In this chapter you will learn:
- Create JSON object from string
- How to use JSON.parse() to create JSON object
- How to control and use the parsing options in JSON parsing
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
<![CDATA[ <!--from j a v a2s .c om-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var book = {
title: "JavaScript",
authors: ["J" ],
edition: 3,
year: 2011
};
var jsonText = JSON.stringify(book);
document.writeln(jsonText);
</script>
</head>
<body>
</body>
</html>
JSON.parse()
A JSON string can be passed directly into
JSON.parse()
and it creates an appropriate JavaScript value.
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><!-- j av a 2 s . c om-->
<html>
<head>
<script type="text/javascript">
var book = {
"title": "JavaScript",
"authors": ["J"],
edition: 3,
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>
Next chapter...
What you will learn in the next chapter:
- How to use JSON.stringify() to convert object to JSON string
- How to control the string indention in JSON
- How to indent JSON string value during serialization
- How to use toJSON() Method