douglascrockford / JSON-js

JSON in JavaScript
http://www.JSON.org/
8.7k stars 4.59k forks source link

Update json2.js #49

Closed chelitotochkaru closed 11 years ago

chelitotochkaru commented 11 years ago

Fixes all Date string with '\/Date(1335205592410)' format.

douglascrockford commented 11 years ago

No thank you.

chelitotochkaru commented 11 years ago

OK. You should check your RegEx pattern because it doesn't work with a DateTime-string returned by JSON.

douglascrockford commented 11 years ago

Do you have a bug report?

chelitotochkaru commented 11 years ago

Yes, I have. I needed parse a JSON response and I found your JS implementation. When I used it I had one error with DateTime properties. In the file I've found the explanation of REVIVAL callback and one example managing a DateTime string. That function has a regex pattern to detect a DateTime format in a string. It doesn't work because it's wrong.

Try to parse the JSON below with the current library and check yourself:

//------------------------------ //JSON Object var dataString = '{ "Id":24,"PassengerName":"Gajardo, Marcelo","PassengerId":72,"CheckIn":"\/Date(1367722800000)\/","CheckOut":"\/Date(1368586800000)\/","Adult":1,"Child":0 }';

//uses the library to cast a string to JSON. var passenger = JSON.parse(data);

//The PassengerName property is type of String. Right cast. var isMe = passenger.PassengerName.indexOf('Gajardo') > -1;

//The CheckIn property is type of DateTime. Wrong cast. var strLocalDate = passenger.CheckIn.toLocaleString();

//------------------------------

Regards!

aeurielesn commented 11 years ago

I'm sorry for jumping into this conversation. But, I believe you, @chelito-gajardo, misunderstood the purpose of the reviver parameter. In your case you need a different one since that one doesn't meet your needs. For instance,

myData = JSON.parse(dataString, function(key, value) {
    var milliseconds;
    if (typeof value === 'string') {
        milliseconds = /^\/Date\((\d+)\)\/$/.exec(value);
        if (milliseconds) {
            return new Date(+milliseconds[1]);
        }
    }
    return value;
});
chelitotochkaru commented 11 years ago

Hi @aeurielesn! I didn't. I believe that the JSONParser must get a real Date type; in all cases should it try to apply the correctly logic to get it, otherwise, it returns the original value.