Date type is not allowed in JSON.
If we need to have a date, we have to include it as a string and then we can convert it back to date object later
var text = '{"name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.write(obj.name + ", " + obj.birth)
Also we can use the second parameter of the
JSON.parse()
function, called
reviver
that checks each property, before returning the value
var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text, function (key, value) {
if (key == "birth") {
return new Date(value);
} else {
return value;
}
});
document.write(obj.name + ", " + obj.birth)