JavaScript Json.stringify replacer converts values to string
datetime, javascript, json
Solution
Try
Date.prototype.toJSON = function() {
return "Date(" + this.getTime() + ")";
};
Without the replacer.
Problem
I am using the javascript JSON.stringify function with a replacer (second parameter) to format date values in a certain way: ``` var s = JSON.stringify(data, function (key, value) { if (key === "") return value; if (jQuery.type(value) === "date") return "Date(" + value.getTime() + ")"; return value; }); ``` I have valid datetime values in my object "data". However, when the replacer function is executed with this value, the datetime value is automatically converted to a string and therefore jQuery.type(value) = "string" and not "date" anymore. I could simply replace all datetime values in the value-object before I call stringify, but I would prefer not to modify the original data. Is this how the replacer function should behave or is this a strange feature of IE (I'm using IE9)? How could I solve this problem?