简体   繁体   中英

JSON.stringify and JSON.parse doesn't work with date objects

This happens in Google Chrome:

var obj  = {"date" : new Date()};
var objJSON = JSON.stringify(obj);
//"{"date":"2014-04-30T07:35:29.002Z"}"
var objBack = JSON.parse(objJSON);

objBack is not a date object is a string. I need to do:

objBack.date = new Date(objBack.date)

Is there a way to get back a Date Object directly?

I need that because I've a complex object (with lots of dates there) which is stored in localStorage using JSON.stringify, after I get back this object from localStorage using JSON.parse, so It'd be great get the dates as Date Object not as strings.

UPD: the answer https://stackoverflow.com/a/15120418/1016033 is more general and don't override default toJSON method if Date .


JSON.stringify calls toJSON method of objects if there is one. So you could add toJSON method to Date prototype.

JSON.parse has second argument function that is called for every parsed value and could be used to call new Date for some values.

Here is small example of how they works:

Date.prototype.toJSON = function() {
    return 'date:' + (+this);
}

var obj = {
    date: new Date,
    s: 'string',
    n: 42
};

console.log(obj);

var json = JSON.stringify(obj);

console.log(json);

function revive(k, v) {
    if (typeof v == 'string' && v.indexOf('date:') == 0) {
        return new Date(+(v.slice(5)));
    }
    return v;
}

var objBack = JSON.parse(json, revive);

console.log(objBack);

The result:

~$ node a.js
{ date: Wed Apr 30 2014 12:09:11 GMT+0400 (MSK),
  s: 'string',
  n: 42 }
{"date":"date:1398845351567","s":"string","n":42}
{ date: Wed Apr 30 2014 12:09:11 GMT+0400 (MSK),
  s: 'string',
  n: 42 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM