Since you are using jQuery, I have expanded the functionality of $.parseJSON() so that it can do this conversion for you automatically and transparently .
It does not convert only .net dates, but also ISO dates. ISO dates are supported by built-in JSON converters in all major browsers, but they only work in one way, since the JSON specification does not support the date data type.
Read all the details (don't want to copy the contents of the blog post because that would be too much) to my blog post and get the code as well. The idea remains the same: change the default jQuery behavior of $.parseJSON() so that it can detect .Net and ISO dates and automatically convert them when parsing JSON data. Thus, you do not need to go through your analyzed objects and convert dates manually.
How is it used?
$.parseJSON(yourJSONstring, true);
See the extra variable? This ensures that all your existing code works as expected without any changes. But if you provide an additional parameter and set it to true , it will determine the dates and convert them accordingly.
Why is this solution better than manual conversion? (proposed by Juan)
- Because you lower the risk of the human forgetting factor in order to transform some variable into your tree of objects (objects can be deep and wide). A.
- Since your code is under development and if you change the part of the server that returns JSON to the client (rename variables, add new ones, delete existing ones, etc.), you should consider these manual conversions on the client side as well. If you do this automatically, you do not need to think (or do anything) about it.
Two main reasons from the head.
Overriding jQuery functionality erroneously
If you donβt want to actually override the existing $.parseJSON() functions, you can minimize the code and rename the extension to $.parseJSONwithdates() , and then always use your own function when parsing JSON. But you may have a problem when you set your Ajax calls to dataType: "json" , which automatically calls the original parser. If you use this parameter, you will have to override the existing jQuery functions.
Itβs also good that you donβt modify the jQuery library source file. You add this extension to a separate file and use it as you wish. Some pages may use it, others may not. But itβs wise to use it everywhere, otherwise you have the same problem of the human factor, forgetting to include the extension. Just add the extension to some global Javascript file (or main page / template) that you can use.
source share