A while back I blogged about the what I thought was oddly lacking from JavaScript - a literal syntax for Date objects, and proposed a Date literal syntax such as @11/14/2006 11:12:02 AM@, while admitting it was wishful thinking, since it was unlikely it would happen anytime soon, and even if it did, wouldn't be something that could be depended on for a number of years until it became ubiquitous enough.
In response to yesterday's post about the Web Development Helper, and its new JSON viewer, there was a comment about the tool not understanding something like new Date(...) in the JSON content. That is true, and by design. The tool only parses true JSON, also sometimes referred to as safe JSON, which is a subset of JavaScript that only uses literal syntax for primitives, objects, and arrays. The tool doesn’t attempt to parse arbitrary JavaScript, not even expressions such as new.
So what about Dates? They are certainly still just as interesting from a serialization perspective. At the same time, we wanted to specifically ensure our serialization format adhered to the actual definition of the JSON syntax. Since I blogged about the @-based syntax, we went ahead and implemented it (in both ASP.NET Ajax and Script#). Actually we implemented a slightly different version, so it wouldn’t require any new JavaScript syntax. We specifically serialize the syntax above as a string with some easily identifiable markers. So say I had an object with a currentDate property. That would get serialized as:
{ currentDate: "@1163531522089@" }
The string has to begin and end with "@". The number in between the @ characters is the number of milliseconds since Jan 1st 1970 (which is what we can get from JavaScript) in the normalized UTC equivalent.
On the server, the JSON parser looks for the special string, and knows to construct a CLR DateTime object. On the client, we have a bit of regex that easily turns this into an equivalent new Date(...) before we call eval to perform the actual JSON deserialization.
Posted on Tuesday, 11/14/2006 @ 12:46 PM
| #
Ajax