Loading ...
Sorry, an error occurred while loading the content.

Re: Dates do not automatically decode

Expand Messages
  • Douglas Crockford
    ... A well written application will have expectations for the types of its value. So you could wrap such uses with your dataValue function. myDate =
    Message 1 of 9 , Dec 5, 2006
    • 0 Attachment
      > Is there a strategy for decoding dates that could or should be in
      > json.js? It seems incomplete that it can encode dates but doesn't
      > automatically decode them into Date objects as well. It is nice when
      > life is a two way street. Is it too restrictive to require that any
      > string with the regexp is turned into a date object?

      A well written application will have expectations for the types of its
      value. So you could wrap such uses with your dataValue function.

      myDate = dateValue(json.date);

      ECMAScript Fourth Edition's String.prototype.parseJSON method will
      take an optional hook function which will have a chance to filter
      every object in the structure. So you can look for date objects. You
      could also replace Data.prototype.toJSONString with a function that
      generates those date objects.
    • Greg Patnude
      You can use my JavaScript utility object to return a data, time, or timestamp -- // VC-DATE /* PROJECT: JDM (Java Dynamic Machine) PROGRAMMER: G. Patnude
      Message 2 of 9 , Dec 5, 2006
      • 0 Attachment
        You can use my JavaScript utility object to return a data, time, or
        timestamp --

        // VC-DATE
        /*

        PROJECT: JDM (Java Dynamic Machine)
        PROGRAMMER: G. Patnude (gpatnude@...)
        FILE: vc-date/vc-date.js
        PURPOSE: DATE & TIME MANIPULATION ROUTINES...

        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *

        COPYRIGHT NOTICE: Copyright 2006 - iDynaTECH, inc.

        This software is distributed under the JSON license and may be
        re-distributed free of charge provided that
        appropriate credit is given to Gregory P. Patnude and iDynaTECH, inc.

        CONTACT INFO:

        Mr. Gregory P. Patnude
        Vice President, Innovations & Applications Group

        Interactive Dynamic Technologies, Incorporated
        dba: iDynaTECH, inc.
        120 North Pine Street
        Suite #162
        Spokane, WA. 99202
        (509) 343 - 3104

        WEB SITE: http://www.idynatech.com
        E-MAIL: gpatnude@...

        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *

        */

        var JSDATE = {

        // CLASS VARIABLES...
        version : "0.000a",
        data: new Object(),
        months: Array('January', 'February', 'March', 'April', 'May',
        'June', 'July', 'August', 'September', 'October', 'November', 'December'),
        days : Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
        'Friday', 'Saturday'),

        // CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS *
        CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS *
        // CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS *
        CLASS FUNCTIONS * CLASS FUNCTIONS * CLASS FUNCTIONS *

        // CONSTRUCTOR...
        init: function init (data) {

        this.data = data;
        return;

        },

        // test: function test(str) {
        test: function test(str) {

        // USE REGULAR EXPRESSIONS TO TEST THE CURRENT FORMAT OF THE
        SUPPLIED ARGUMENT...
        var tests = [

        ["TIMESTAMP", new
        RegExp(/\d{4}\-\d{2}\-\d{2}\W\d{2}\:\d{2}\:\d{2}\.\d/ig)],
        ["DATE", new RegExp(/\d{4}\-\d{2}\-\d{2}/ig)],
        ["TIME", new RegExp(/\d{2}\:\d{2}\:\d{2}\.\d/ig)],

        ];

        // WHILE LOOPING THROUGH EACH TEST...
        for (var t in tests) {

        // PERFORM THE TEST AGAINST THE SUPPLIED ARGUMENT
        AND RETURN IT PROPERLY FORMATTED...
        var branch = (tests[t][1].test(str)) ? tests[t][0] :
        null;

        // NOW --> TO PROPERLY FORMAT THE ARGUMENT...
        if (branch) {

        // EVAL AND FORCE A CALL TO THE FORMATTER
        FOR THIS TYPE...
        eval("dx = this." + branch + "(str,
        tests[t][1])");
        return dx;

        }

        }

        },

        // CONVERTS A DATE TO AN OBJECT...
        DATE: function DATE(d, test) {

        var ds = d.split("-");
        var dt = new Date(ds[0], (ds[1] - 1), ds[2]);
        dt.type = 'DATE';

        dt.year = parseInt(ds[0]);
        dt.month = parseInt(ds[1]);
        dt.day = parseInt(ds[2]);

        return dt;

        },

        // CONVERTS A TIME TO AN OBJECT...
        TIME: function TIME(t, test) {

        var ts = t.split(":");
        var msec = ts[2].split(".");
        var tt = new Date(0, 0, 0, ts[0], ts[1], msec[0], msec[1]);

        tt.type = 'TIME';

        tt.hour = parseInt(ts[0]);
        tt.minute = parseInt(ts[1]);
        tt.sec = parseInt(msec[0]);
        tt.msec = parseInt(msec[1]);

        return tt;

        },

        // CONVERTS A TIMESTAMP TO AN OBJECT...
        TIMESTAMP: function TIMESTAMP(ts, test) {

        // UTIL.trace("TIMESTAMP() called with: " + ts + ", " + test
        + ", " + r + ", " + c);
        // var tso = new Object();
        var tx = ts.split(new RegExp(/\ /gi));
        var ds = tx[0].split("-");
        var ts = tx[1].split(":");
        var msec = ts[2].split(".");
        var tso = new Date(ds[0], (ds[1] - 1), ds[2], ts[0], ts[1],
        msec[0], msec[1]);
        tso.type = 'TIMESTAMP';
        return tso;

        }

        // EOF

        };



        -----Original Message-----
        From: json@yahoogroups.com [mailto:json@yahoogroups.com] On Behalf Of Peter
        Michaux
        Sent: Monday, December 04, 2006 5:30 PM
        To: json@yahoogroups.com
        Subject: [json] Dates do not automatically decode

        Hi,

        Is there a strategy for decoding dates that could or should be in
        json.js? It seems incomplete that it can encode dates but doesn't
        automatically decode them into Date objects as well. It is nice when
        life is a two way street. Is it too restrictive to require that any
        string with the regexp is turned into a date object?

        \d{4}-\d{2}-\d{2}T\d{2}\:\d{2}:\d{2}

        I know this picks invalid dates. Perhaps some more inspection to
        insure it is a date. If it is not a real date then it should be left
        as a string? This seems like an expensive process and might be better
        to allow people to just loose out if the have a json string with an
        invalid date.

        I made some experiements with YAML in Ruby and when a date is loaded
        it seems to stay as a string as does the JSON code. It seems confusing
        that this is ok that the conversions are not perfectly reversable.

        Any thoughts on this?

        Thanks,
        Peter
      • Peter Michaux
        Hi Douglas, ... Any chance you will be adding this capability to the http://json.org/json.js file? ... This seems a little confusing. toJSONString generates
        Message 3 of 9 , Dec 5, 2006
        • 0 Attachment
          Hi Douglas,

          On 12/5/06, Douglas Crockford <douglas@...> wrote:
          >

          > ECMAScript Fourth Edition's String.prototype.parseJSON method will
          > take an optional hook function which will have a chance to filter
          > every object in the structure.

          Any chance you will be adding this capability to the
          http://json.org/json.js file?

          > So you can look for date objects. You
          > could also replace Data.prototype.toJSONString with a function that
          > generates those date objects.

          This seems a little confusing. "toJSONString" generates strings. Do
          you mean it would generate a string like "new Date(2006, 05, 18, ...)"
          so that when the JSON is eval'ed it autmatically converted to and
          object. I doubt you mean this because it is not portable. Is the
          "toJSONString" function involved in parsing JSON strings?

          Thanks,
          Peter
        • Mark Miller
          ... Cool. Is there a draft we can read? -- Text by me above is hereby placed in the public domain Cheers, --MarkM
          Message 4 of 9 , Dec 5, 2006
          • 0 Attachment
            Douglas Crockford wrote:
            > ECMAScript Fourth Edition's String.prototype.parseJSON method will
            > take an optional hook function which will have a chance to filter
            > every object in the structure.

            Cool. Is there a draft we can read?


            --
            Text by me above is hereby placed in the public domain

            Cheers,
            --MarkM
          • Douglas Crockford
            BAD: eval( dx = this. + branch + (str, tests[t][1]) ); BETTER: dx = this[branch](str, tests[t][1]);
            Message 5 of 9 , Dec 5, 2006
            • 0 Attachment
              BAD:

              eval("dx = this." + branch + "(str, tests[t][1])");

              BETTER:

              dx = this[branch](str, tests[t][1]);
            • Douglas Crockford
              ... You are right, it would be bad to generate a string like new Date . Instead, you would generate an object that would be recognized by your hook function
              Message 6 of 9 , Dec 5, 2006
              • 0 Attachment
                > > ECMAScript Fourth Edition's String.prototype.parseJSON method will
                > > take an optional hook function which will have a chance to filter
                > > every object in the structure.
                >
                > Any chance you will be adding this capability to the
                > http://json.org/json.js file?
                >
                > > So you can look for date objects. You
                > > could also replace Data.prototype.toJSONString with a function that
                > > generates those date objects.

                > Do
                > you mean it would generate a string like "new Date(2006, 05, 18, ...)"
                > so that when the JSON is eval'ed it autmatically converted to and
                > object. I doubt you mean this because it is not portable. Is the
                > "toJSONString" function involved in parsing JSON strings?

                You are right, it would be bad to generate a string like "new Date".
                Instead, you would generate an object that would be recognized by your
                hook function to parseJSON. For example,

                date.toJSONString = function () {
                return '{"type": "date", "value": ' + this.valueOf() +
                '}';
                };
              • Douglas Crockford
                ... http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html
                Message 7 of 9 , Dec 5, 2006
                • 0 Attachment
                  > > ECMAScript Fourth Edition's String.prototype.parseJSON method will
                  > > take an optional hook function which will have a chance to filter
                  > > every object in the structure.

                  > Cool. Is there a draft we can read?

                  http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html
                • Peter Michaux
                  Hi, ... I read the proposal and wonder if there is some loose wording for parseJSON. I doubt it but would like to double check. The optional hook function
                  Message 8 of 9 , Dec 5, 2006
                  • 0 Attachment
                    Hi,

                    On 12/5/06, Douglas Crockford <douglas@...> wrote:
                    >
                    > > > ECMAScript Fourth Edition's String.prototype.parseJSON method will
                    > > > take an optional hook function which will have a chance to filter
                    > > > every object in the structure.
                    >
                    > > Cool. Is there a draft we can read?
                    >
                    > http://developer.mozilla.org/es4/proposals/json_encoding_and_decoding.html


                    I read the proposal and wonder if there is some loose wording for
                    parseJSON. I doubt it but would like to double check.

                    "The optional hook function will be called for each object value
                    found. It is passed each object. Its return value will be used instead
                    of the object in the final structure."

                    If only "each object value" is run through the hook function then this
                    won't allow for a date string to be run though the hook function and
                    converted to a Date object. This is because a the string produced by
                    eval is a primitive. Should "each object value" be changed to "each
                    node value" or "each object property value"?

                    If the wording is correct is it up to me too loop through the object
                    properties manually in my hook function? A "yes you must do the
                    looping" answer to this would be satisfy my curiosity.

                    I tested the different interpretations with two functions that
                    simulate parseJSON. I am using a namespaced library so it is a little
                    different set up but I took the parseJSON function from
                    http://www.json.org/json.js as the starting point. Also I don't
                    augment prototypes so I have used for-in loops without checking own
                    property.

                    Douglas, could you please confirm which implementation is the intended
                    one for the hook function.

                    Thank you,
                    Peter


                    // My literal interpretation from the proposed JSON API

                    FORK.Json.load = function (str, hook) {
                    try {
                    if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u
                    \n\r\t])+?$/.test(str)) {

                    var obj = eval('(' + str + ')');

                    if (hook) {

                    obj = (function(o) {
                    if (typeof o == 'object') {
                    for (var p in o) {
                    o[p] = arguments.callee(o[p]);
                    }
                    return hook(o);
                    } else {
                    return o;
                    }
                    })(obj);

                    }
                    return obj;
                    }
                    } catch (e) {}

                    throw new SyntaxError("parseJSON");
                    };


                    // This could be what is intended implementation of the proposed hook function.

                    FORK.Json.load = function (str, hook) {
                    try {
                    if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u
                    \n\r\t])+?$/.test(str)) {

                    var obj = eval('(' + str + ')');

                    if (hook) {
                    obj = (function(o) {
                    if (typeof o == 'object') {
                    for (var p in o) {
                    o[p] = arguments.callee(o[p]);
                    }
                    }
                    return hook(o);
                    })(obj);
                    }
                    return obj;
                    }
                    } catch (e) {}

                    throw new SyntaxError("parseJSON");
                    };
                  Your message has been successfully submitted and would be delivered to recipients shortly.