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 ww . ja va 2 s . com-->
year: 2011
};
var jsonText = JSON.stringify(book);
document.writeln(jsonText);
</script>
</head>
<body>
</body>
</html>
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, <!-- w ww . jav a 2 s . c o m-->
year: 2011
};
var jsonText = JSON.stringify(book);
document.writeln(jsonText);
var bookCopy = JSON.parse(jsonText);
document.writeln(bookCopy);
</script>
</head>
<body>
</body>
</html>
An error is thrown if the text passed into JSON.parse()
is not valid JSON.
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, <!-- ww w. j av a2 s .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>