JSON.parse(str)
will not convert date string to date object and we get an error
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str);
document.write( meetup.date.getDate() ); // Error!
The value of
meetup.date
is a string, not a
Date
object.
That is why
JSON.parse
was unable to transform that string into a
Date
object.
...
Passing the reviving function to
JSON.parse
as the second argument fixes the issue.
The reviving function returns all values “as is”, but
date
will become a
Date
object and the error will not occur
let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';
let meetup = JSON.parse(str, function(key, value) {
if (key == 'date') return new Date(value);
return value;
});
alert( meetup.date.getDate() ); // now works!