Reputation: 1449
I am working in ASP.NET MVC 5. I am trying to deserialize dates coming from the server in JSON format. The JSON arrives and when I try to deserialize the dates the debugger just stops and don't show any errors other the in the console, which I can't understand. This is my code so far:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: '/Home/GetDates',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (dates) {
var date = dates[0];
var desDate = $.parseJSON(date, true);
console.log(desDate);
}
});
});
Here are some pics on the errormessage and that a have data coming in.
Here is a link to the docs I have been looking at. Docs
Upvotes: 0
Views: 121
Reputation: 42044
Because you are referring to this jQuery parseJSON automatic date conversion for Asp.net and ISO date strings you need to include the jQuery extension defined there.
Indeed, in jQuery parseJSON(jsonString) accepts only one argument while you are using an extension.
Moreover, your dates variable is an array of string, and not a json string.
//
// Look at the end....
//
/*
* jQuery.parseJSON() extension (supports ISO & Asp.net date conversion)
*
* Version 1.0 (13 Jan 2011)
*
* Copyright (c) 2011 Robert Koritnik
* Licensed under the terms of the MIT license
* http://www.opensource.org/licenses/mit-license.php
*/
(function ($) {
// JSON RegExp
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var dateISO = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.,]\d+)?Z/i;
var dateNet = /\/Date\((\d+)(?:-\d+)?\)\//i;
// replacer RegExp
var replaceISO = /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:[.,](\d+))?Z"/i;
var replaceNet = /"\\\/Date\((\d+)(?:-\d+)?\)\\\/"/i;
// determine JSON native support
var nativeJSON = (window.JSON && window.JSON.parse) ? true : false;
var extendedJSON = nativeJSON && window.JSON.parse('{"x":9}', function (k, v) {
return "Y";
}) === "Y";
var jsonDateConverter = function (key, value) {
if (typeof(value) === "string") {
if (dateISO.test(value)) {
return new Date(value);
}
if (dateNet.test(value)) {
return new Date(parseInt(dateNet.exec(value)[1], 10));
}
}
return value;
};
$.extend({
parseJSON: function (data, convertDates) {
/// <summary>Takes a well-formed JSON string and returns the resulting JavaScript object.</summary>
/// <param name="data" type="String">The JSON string to parse.</param>
/// <param name="convertDates" optional="true" type="Boolean">Set to true when you want ISO/Asp.net dates to be auto-converted to dates.</param>
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = $.trim(data);
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data
.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
// Try to use the native JSON parser
if (extendedJSON || (nativeJSON && convertDates !== true)) {
return window.JSON.parse(data, convertDates === true ? jsonDateConverter : undefined);
}
else {
data = convertDates === true ?
data.replace(replaceISO, "new Date(parseInt('$1',10),parseInt('$2',10)-1,parseInt('$3',10),parseInt('$4',10),parseInt('$5',10),parseInt('$6',10),(function(s){return parseInt(s,10)||0;})('$7'))")
.replace(replaceNet, "new Date($1)") :
data;
return (new Function("return " + data))();
}
} else {
$.error("Invalid JSON: " + data);
}
}
});
})(jQuery);
var date = '{"date": "\\/Date(1498435200000)\\/"}';
var desDate = $.parseJSON(date, true);
console.log(desDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1
Reputation: 318172
The data returned from the ajax call is already parsed, so dates
is an array containing strings, and dates[0]
is the string/Date(14984....)/
etc.
To parse the string, remove everything but the numbers, and use that timestamp to create a Date object.
$(document).ready(function () {
$.ajax({
type : 'GET',
url : '/Home/GetDates',
dataType : "json",
contentType : "application/json; charset=utf-8",
success: function (dates) {
var d = dates[0];
var unix = +d.replace(/\D/g, '');
var date = new Date(unix);
var desDate = date.getFullYear() + '/' +
(date.getMonth()+1) + '/' +
date.getDate();
console.log(desDate);
}
});
});
Upvotes: 2
Reputation: 30739
You need to execute the JavaScript inside your string variable as
var dateVar = eval(dates[0]);
This will give you the date but not in a proper format which you want. For the proper format user either moment.js
or simply create your own lines of code like
var finalDate = new Date(dateVar).toISOString().split('T')[0];
console.log(finalDate);
The new Date()
is again needed here so that we can make use of toISOString()
and get the proper date format.
Upvotes: 1