欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

IE低版本 JSON.parse 和stringify 的兼容 (IE8以下)

程序员文章站 2023-02-15 21:26:09
低版本的IE不支持JSON,JSON对象解析不是随着javascript产生的,找到一段兼容常用的JSON.parse和JSON.stringify的代码 1 if (!window.JSON) { 2 window.JSON = { 3 parse: function(jsonStr) { 4 r... ......

  低版本的IE不支持JSON,JSON对象解析不是随着javascript产生的,找到一段兼容常用的JSON.parse和JSON.stringify的代码

1 if (!window.JSON) { 2 window.JSON = { 3 parse: function(jsonStr) { 4 return eval('(' + jsonStr + ')'); 5 }, 6 stringify: function(jsonObj) { 7 var result = '', 8 curVal; 9 if (jsonObj === null) { 10 return String(jsonObj); 11 } 12 switch (typeof jsonObj) { 13 case 'number': 14 case 'boolean': 15 return String(jsonObj); 16 case 'string': 17 return '"' + jsonObj + '"'; 18 case 'undefined': 19 case 'function': 20 return undefined; 21 } 22 23 switch (Object.prototype.toString.call(jsonObj)) { 24 case '[object Array]': 25 result += '['; 26 for (var i = 0, len = jsonObj.length; i < len; i++) { 27 curVal = JSON.stringify(jsonObj[i]); 28 result += (curVal === undefined ? null : curVal) + ","; 29 } 30 if (result !== '[') { 31 result = result.slice(0, -1); 32 } 33 result += ']'; 34 return result; 35 case '[object Date]': 36 return '"' + (jsonObj.toJSON ? jsonObj.toJSON() : jsonObj.toString()) + '"'; 37 case '[object RegExp]': 38 return "{}"; 39 case '[object Object]': 40 result += '{'; 41 for (i in jsonObj) { 42 if (jsonObj.hasOwnProperty(i)) { 43 curVal = JSON.stringify(jsonObj[i]); 44 if (curVal !== undefined) { 45 result += '"' + i + '":' +curVal + ','; 46 } 47 } 48 } 49 if (result !== '{') { 50 result = result.slice(0, -1); 51 } 52 result += '}'; 53 return result; 54 55 case '[object String]': 56 return '"' + jsonObj.toString() + '"'; 57 case '[object Number]': 58 case '[object Boolean]': 59 return jsonObj.toString(); 60 } 61 } 62 }; 63 }