Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Json.stringify replacer converts values to string

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?

like image 291
Preli Avatar asked Apr 09 '26 02:04

Preli


1 Answers

Try

Date.prototype.toJSON = function() {
     return "Date(" + this.getTime() + ")";
};

Without the replacer.

like image 135
Esailija Avatar answered Apr 11 '26 16:04

Esailija