2013-04-23 20 views
2

我在json格式的jQuery-ajax響應中解析日期時遇到問題。在jQuery中解析iso日期ajax json響應

我的客戶端代碼:

$.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解析期間自動解析

克里斯

回答

1

就這樣

var myDate = new Date("2013-07-01T00:00:00") 

的JavaScript支持ISO 8601解析開箱

+1

但如果我有10000個元素與複雜類型在我的JSON響應? – cryss 2013-04-23 18:28:49

+1

你必須後處理每一個。有一些有趣的意見在這個問題上是類似於你:http://stackoverflow.com/questions/206384/how-to-format-a-json-date – 2013-04-23 18:29:49

+0

我在找東西什麼可以自動解析日期整個json樹 – cryss 2013-04-23 18:29:54

5

好吧,我已經找到了一個很好的解決方案,從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); 
    } 
}); 
+1

你真的只是用'很好'這個!? ;-D – 2014-09-16 23:30:57