How to parse JSON to receive a Date object in JavaScript?

Piotr Owsiak picture Piotr Owsiak · Dec 22, 2010 · Viewed 225.1k times · Source

I have a following piece of JSON:

\/Date(1293034567877)\/

which is a result of this .NET code:

var obj = DateTime.Now;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
serializer.Serialize(obj).Dump();

Now the problem I am facing is how to create a Date object from this in JavaScript. All I could find was incredible regex solution (many containing bugs).

It is hard to believe there is no elegant solution as this is all in JavaScrip, I mean JavaScript code trying to read JSON (JavaScript Object Notation) which is supposed to be a JavaScript code and at this moment it turns out it's not cause JavaScript cannot do a good job here.

I've also seen some eval solutions which I could not make to work (besides being pointed out as security threat).

Is there really no way to do it in an elegant way?

Similar question with no real answer:
How to parse ASP.NET JSON Date format with GWT

Answer

Tim picture Tim · Jan 24, 2013

The JSON.parse function accepts an optional DateTime reviver function. You can use a function like this:

dateTimeReviver = function (key, value) {
    var a;
    if (typeof value === 'string') {
        a = /\/Date\((\d*)\)\//.exec(value);
        if (a) {
            return new Date(+a[1]);
        }
    }
    return value;
}

Then call

JSON.parse(somejsonstring, dateTimeReviver);

And your dates will come out right.