This project is archived and is in readonly mode.

#710 ✓duplicate

JSON.encode for Date objects returns null

Reported by elado | July 12th, 2009 @ 11:59 PM | in 2.0 (closed)

Couldn't figure out if this is a bug or intended (due to formats handling).

alert(JSON.encode(new Date())); // null!


Comments and changes to this ticket

  • Daniele C.

    Daniele C. July 14th, 2009 @ 01:59 PM

    Look, if you change the JSON.encode function in this way:

    @@@ Javascript encode: function(obj){

    switch ($type(obj)){
        case 'string':
            return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"';
        case 'array':
            return '[' + String( + ']';
        case 'object': case 'hash':
            var string = [];
            Hash.each(obj, function(value, key){
                var json = JSON.encode(value);
                if (json) string.push(JSON.encode(key) + ':' + json);
            return '{' + string + '}';
        case 'number': case 'boolean': return String(obj);
        //Start Changes
        case 'date': return 'new Date("'+obj.toString()+'")';
        //End Changes
        case false: return 'null';
    return null;


    You can parse also Date object. The problem is the syntax of Date.prototype.toString that changes from a Browser to another, if you use a ServerSide script to generate the JSON you must control the Browser first and print the corresponding String for the Date Object, that is not very comfortable.
  • Sebastian Markbåge

    Sebastian Markbåge July 23rd, 2009 @ 02:43 AM

    • Assigned user set to “Sebastian Markbåge”
    • State changed from “new” to “open”

    There's no agreed upon standard for Date serialization in JSON. Some people use the Date object constructor which isn't valid JSON. Some people use seconds or miliseconds or an ISO 8601 string which you can't distinguish from regular numbers or strings with similar values.

    However, encode should probably fall back to ISO 8601 strings on dates since that's what Firefox's native implementation is doing.

  • Scott Kyle

    Scott Kyle July 23rd, 2009 @ 11:19 PM

    Isn't this murky waters since if we implemented this, then we'd also have to implement handling dates in JSON.decode? :-/

  • Scott Kyle

    Scott Kyle September 10th, 2009 @ 02:25 PM

    This will be resolved in 2.0

  • Scott Kyle

    Scott Kyle September 10th, 2009 @ 02:29 PM

    • State changed from “open” to “duplicate”

    Since this is a duplicate of #658, I will mark it as such.

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Shared Ticket Bins