I’m attempting to parse JSON response to convert ASP.NET dates to javascript dates.
The actual response looks like so:
{"Id":1,"Title":null,"Description":null,"Content":null,"PropagateModel":false,"Status":0,"ComponentPublishDate":"\/Date(1340299653555)\/"}
I extended the javascript string object to do the regex conversion from \/Date(1340299653555)\/ to new Date(1340298914781)
String.prototype.parseWithJSONDate = function () {
return this.replace(/\/Date\((.*?)\)\//gi, 'new Date($1)');
};
Then i setup a converter filter to do the actual parsing.
$.ajaxSetup({
dataFilter: function(data, dataType) {
if (dataType === "json") {
return data.parseWithJSONDate();
}
return data;
}
});
This converter doesn’t work. The first issue i had with it was that the response would get corrupted somehow after the converter returns. I fixed that by calling JSON.parse like so return JSON.parse(res) at the end of function. Why in the world do i need to parse a string that’s already a JSON string??
The second issue is that actual regex doesn’t appear to be replacing values. The odd thing is i tested it outside of the function on a sample JSON string and it worked just fine.
Can anybody suggest anything? Thanks!
UPDATE 1
I think i figured out the answer to my first question. My converter was running for json and text data types. Which is likely the reason why i had to explicitly convert the return value to JSON. I removed text data type from the converter and updated the rest of the code accordingly.
UPDATE 2
I ended up creating a new view model where date is a formatted string. Not the best thing in world, but better than screwing around with jQuery ajax events.
I ended up converting all dates to appropriate format on the server and returning the value to client. Not the optimal solution, but i couldn’t figure out how to convert with data filters.