【问题标题】:$.parseJSON(data, true) throws$.parseJSON(data, true) 抛出
【发布时间】:2017-06-28 13:54:18
【问题描述】:

我正在使用 ASP.NET MVC 5。 我正在尝试以 JSON 格式反序列化来自服务器的日期。 JSON 到达,当我尝试反序列化日期时,调试器会停止并且不会在控制台中显示任何其他错误,这是我无法理解的。 到目前为止,这是我的代码:

$(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);
    }

});

});

这里有一些关于错误消息的图片,并且有数据进来。

这是我一直在查看的文档的链接。 Docs

【问题讨论】:

  • 希望输出是什么样的?
  • JSON 已被解析!这就是将dataType 设置为json 所做的事情,它会为您解析它。再次解析总是会抛出错误。
  • 类似:2014/06/06。我知道也许我必须通过更多格式设置日期,但截至目前我无法通过 JSON -> JS
  • 同样,dates 已经被解析,dates[0] 是字符串 /Date(14984....)/,这不是有效的 JSON,因此无法解析
  • 类似var d = new Date( +date.replace(/\D/g, '') )

标签: javascript jquery json asp.net-ajax


【解决方案1】:

ajax调用返回的数据已经解析过了,所以dates是一个包含字符串的数组,dates[0]是字符串/Date(14984....)/

要解析字符串,删除除数字之外的所有内容,并使用该时间戳创建一个 Date 对象。

$(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);
        }
    });
});

【讨论】:

  • 这就是我想要的。谢谢你的回答!
【解决方案2】:

你需要在你的字符串变量中执行 JavaScript

var dateVar  = eval(dates[0]);

这会给你日期,但不是你想要的正确格式。对于正确格式的用户,moment.js 或简单地创建自己的代码行,如

var finalDate = new Date(dateVar).toISOString().split('T')[0];
console.log(finalDate);

这里再次需要new Date(),以便我们可以使用toISOString()并获得正确的日期格式。

【讨论】:

  • 谢谢。很快就会调查的。在运行。现在。
【解决方案3】:

因为您指的是这个jQuery parseJSON automatic date conversion for Asp.net and ISO date strings,所以您需要包含那里定义的jQuery 扩展。

确实,在 jQuery 中,parseJSON(jsonString) 在您使用扩展程序时只接受一个参数。

此外,您的日期变量是字符串数组,而不是 json 字符串。

//
// 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);
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 我一定会试试这个。这个问题已经有一段时间了,已经累了。看起来不够近,我错过了它的一部分。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
相关资源
最近更新 更多