Convert string to date when converting string to JSON in JavaScript

Description

The following code shows how to convert string to date when converting string to JSON.

Example


<!--  w w  w .  j  a  v a 2 s .  co  m-->
<!DOCTYPE html>
<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>

Click to view the demo

The code above generates the following result.

Convert string to date when converting string to JSON in JavaScript
Home »
  Javascript Tutorial »
    Data Type »
      JSON
Javascript Tutorial JSON
Add toJSON() method to object and have it r...
Control the string indention converting JSO...
Convert JSON object to String in JavaScript
Convert selected fields from JSON to String...
Convert string to date when converting stri...
Handle field one by one during JSON to stri...
Set indentation character during JSON seria...
Use JSON.parse() to create JSON object from...