javascript - 在 jQuery ajax json 响应中解析 iso 日期

标签 javascript ajax json jquery

我在以 json 格式解析 jQuery-ajax 响应中的日期时遇到问题。

我的客户端代码:

$.ajax({
    url: '/index',
    dataType: 'json',
    success: function (data) {
        console.log(data.date);
    }
});

服务器正在发送 json:

{
    "name": "john",
    "date": "2013-07-01T00:00:00",
}

运行我的客户端代码后,我在控制台中收到一个字符串内容:

2013-07-01T00:00:00

这不是日期类型。我认为这将由解析器完成。我需要做什么才能在 json 解析期间自动解析我的日期?

克里斯

最佳答案

好的,我从 http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html 找到了一个很好的解决方案:

/*!
 * 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)) {
                if (value == '0001-01-01T00:00:00') {
                    return null;
                }

                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);

用法:

$.ajax({
    url: '/index',
    // dataType: 'json', <- remove it
    converters: {
        "text json": function (data) {
            return $.parseJSON(data, true);
        }
    },
    success: function (data) {
        console.log(data.date);
    }
});

关于javascript - 在 jQuery ajax json 响应中解析 iso 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16176514/

相关文章:

javascript - 在后台上下文中的脚本之间进行通信(后台脚本,浏览器操作,页面操作,选项页面等)

javascript - 使用deflate算法实现GZIP解压

javascript - 使用 AJAX 为 plupload 回显值

javascript - 无法读取属性 api Rest

javascript - 具有来自多个 JSON 文件的值的 Highcharts

javascript - 如何在附加事件之前启动js代码?

php - 如何进行ajax登录请求

javascript - 服务器不会同时响应多个 AJAX 请求

java - Jackson 将嵌套对象保存到数据库

json - 如何使用 jsonlite 包将数据从 json 格式导入 R