JSON.parseAjax Method, handling encoded dates in a JSON string.

28. September 2010 14:37

Okay, the availability of JSON.parse and JSON.stringify is awesome in modern browsers. I'm including my modifications to the JSON.org json2.js script to include a method JSON.parseAjax that will revive ISO-8601 and Microsoft Ajax encoded Date strings into a native Date object. I am also checking against the IE version as a bug in IE8's native JSON.parse method may raise an error that you can't catch when you extend the prototype of Array, Function, Object etc.

//parse a test string, where test1 is an ISO-8601 Date, and test2 is an MS-Ajax Date
var obj = JSON.parseAjax('{"test1":"1970-01-01T00:00:00Z", "test2":"\\\/Date(0)\\\/"}');

//object was returned and test1's value equals test2's value
alert( obj && obj.test1.valueOf() == obj.test2.valueOf());

This allows you to handle a number of different methods of returning Date-Time strings from the server. It's worth noting that you should always send date times as UTC based when passing over the wire.

json2-ajax.js (15.25 kb)


Comments are closed


Michael J. Ryan aka Tracker1

My name is Michael J. Ryan and I've been developing web based applications since the mid 90's.

I am an advanced Web UX developer with a near expert knowledge of JavaScript.