Consider this:
var object = {date: new Date()};
JSON.stringify(object, function(key, value) {
console.log('---');
console.log('key:', key);
console.log('value:', value);
console.log('value instanceof Date:', value instanceof Date);
return value;
});
As documentation says:
The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified.
...
If you return any other object, the object is recursively stringified into the JSON string, calling the replacer function on each property, unless the object is a function, in which case nothing is added to the JSON string.
But if you run the code, you will get this:
---
key:
value: { date: Fri Jan 10 2014 02:25:00 GMT+0100 (CET) }
value instanceof Date: false
---
key: date
value: 2014-01-10T01:25:00.262Z
value instanceof Date: false
It means, that the date property was stringified before replacer function has been called. Is it a normal behaviour or am I missing something? How can I affect format of Date
stringification without overriding its default toJSON
method?
Thanks!
Edit
Based on responses and next research, documentation seems to be unclear at this point and toJSON
is beeing called before the replacer function. Based on Pills's response, this snippet should do the job:
var object = {date: new Date };
JSON.stringify(object, function(key, value) {
if (typeof(value) === 'object') {
for (var k in value) {
if (value[k] instanceof Date) {
value[k] = value[k].getTime();
}
}
}
return value;
});
Edit #2
Xotic750's solution is much better than previous one.