Skip to content

Instantly share code, notes, and snippets.

@benfoxall
Created February 6, 2012 17:40
Show Gist options
  • Save benfoxall/1753574 to your computer and use it in GitHub Desktop.
Save benfoxall/1753574 to your computer and use it in GitHub Desktop.
A function for converting .NET dates in json responses
/*!
* $.convertJSONDates
*
* $.getJSON(…).pipe($.convertJSONDates).done(function(data){…})
*
* Based on …
*
* jQuery.parseJSON()
* http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
*
* Copyright (c) 2011 Robert Koritnik
* Licensed under the terms of the MIT license
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
// replacer RegExp
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i;
var dateNet = /\/Date\((\d+)(?:[-\+]\d+)?\)\//i;
var jsonDateConverter = function(value) {
if (typeof(value) === "string")
{
if (dateISO.test(value))
{
return new Date(value);
}
if (dateNet.test(value))
{
return new Date(parseInt(dateNet.exec(value)[1], 10));
}
}
return value;
};
var converter = function(json){
$.each(json || {}, function(k,v){
if(typeof v == 'object'){
if(v !== null){
// recurse
converter(v);
}
} else {
json[k] = jsonDateConverter(v);
}
});
return json;
};
$.convertJSONDates = converter;
})(jQuery);
@SebaVDP
Copy link

SebaVDP commented Apr 3, 2012

Hi,

I receive an exception when I want to get json data with null values.
ex.: { name: "me", value: null }

I changed your converter to make it work.

var converter = function(json){
$.each(json, function(k,v){
if(typeof v == 'object'){
// recurse
if (v != null) {
converter(v);
}
}
else {
json[k] = jsonDateConverter(v);
}
});
return json;
};

Best Regards

Sébastien

@benfoxall
Copy link
Author

Hi Sébastien,

Thanks for letting me know - I've updated this gist with your change.

Ben

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment