解决IE6 IE7 JSON.stringify JSON 未定义问题

做前端我们经常要用到JSON.stringify来将JSON转成字符串,但悲剧的是IE6与IE7并不支持JSON.stringify。下面我们来简单讲一下如何解决IE6 IE7 JSON.stringify JSON 未定义问题。

首先我们需要引入一个json2.js的文件(请在本文下方下载),如果你不想引用一个文件这么麻烦。可以将以下压缩好的代码添加至你的JS文件中(注意代码位置必须靠前)

json2.js

 

[javascript] view plain copy

  1. if (typeof JSON !== 'object') {  
  2.     JSON = {};  
  3. }  
  4.   
  5. (function () {  
  6.     'use strict';  
  7.   
  8.     function f(n) {  
  9.         return n < 10 ? '0' + n : n;  
  10.     }  
  11.   
  12.     if (typeof Date.prototype.toJSON !== 'function') {  
  13.   
  14.         Date.prototype.toJSON = function () {  
  15.   
  16.             return isFinite(this.valueOf())  
  17.                 ? this.getUTCFullYear()     + '-' +  
  18.                     f(this.getUTCMonth() + 1) + '-' +  
  19.                     f(this.getUTCDate())      + 'T' +  
  20.                     f(this.getUTCHours())     + ':' +  
  21.                     f(this.getUTCMinutes())   + ':' +  
  22.                     f(this.getUTCSeconds())   + 'Z'  
  23.                 : null;  
  24.         };  
  25.   
  26.         String.prototype.toJSON      =  
  27.             Number.prototype.toJSON  =  
  28.             Boolean.prototype.toJSON = function () {  
  29.                 return this.valueOf();  
  30.             };  
  31.     }  
  32.   
  33.     var cx,  
  34.         escapable,  
  35.         gap,  
  36.         indent,  
  37.         meta,  
  38.         rep;  
  39.   
  40.   
  41.     function quote(string) {  
  42.   
  43.         escapable.lastIndex = 0;  
  44.         return escapable.test(string) ? '"' + string.replace(escapable, function (a) {  
  45.             var c = meta[a];  
  46.             return typeof c === 'string'  
  47.                 ? c  
  48.                 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);  
  49.         }) + '"' : '"' + string + '"';  
  50.     }  
  51.   
  52.   
  53.     function str(key, holder) {  
  54.   
  55.         var i,          // The loop counter.  
  56.             k,          // The member key.  
  57.             v,          // The member value.  
  58.             length,  
  59.             mind = gap,  
  60.             partial,  
  61.             value = holder[key];  
  62.   
  63.         if (value && typeof value === 'object' &&  
  64.                 typeof value.toJSON === 'function') {  
  65.             value = value.toJSON(key);  
  66.         }  
  67.   
  68.   
  69.         if (typeof rep === 'function') {  
  70.             value = rep.call(holder, key, value);  
  71.         }  
  72.   
  73.   
  74.         switch (typeof value) {  
  75.         case 'string':  
  76.             return quote(value);  
  77.   
  78.         case 'number':  
  79.   
  80.   
  81.             return isFinite(value) ? String(value) : 'null';  
  82.   
  83.         case 'boolean':  
  84.         case 'null':  
  85.   
  86.   
  87.             return String(value);  
  88.   
  89.   
  90.         case 'object':  
  91.   
  92.             if (!value) {  
  93.                 return 'null';  
  94.             }  
  95.   
  96.   
  97.             gap += indent;  
  98.             partial = [];  
  99.   
  100.   
  101.             if (Object.prototype.toString.apply(value) === '[object Array]') {  
  102.   
  103.   
  104.                 length = value.length;  
  105.                 for (i = 0; i < length; i += 1) {  
  106.                     partial[i] = str(i, value) || 'null';  
  107.                 }  
  108.   
  109.   
  110.                 v = partial.length === 0  
  111.                     ? '[]'  
  112.                     : gap  
  113.                     ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'  
  114.                     : '[' + partial.join(',') + ']';  
  115.                 gap = mind;  
  116.                 return v;  
  117.             }  
  118.   
  119.   
  120.             if (rep && typeof rep === 'object') {  
  121.                 length = rep.length;  
  122.                 for (i = 0; i < length; i += 1) {  
  123.                     if (typeof rep[i] === 'string') {  
  124.                         k = rep[i];  
  125.                         v = str(k, value);  
  126.                         if (v) {  
  127.                             partial.push(quote(k) + (gap ? ': ' : ':') + v);  
  128.                         }  
  129.                     }  
  130.                 }  
  131.             } else {  
  132.   
  133.   
  134.                 for (k in value) {  
  135.                     if (Object.prototype.hasOwnProperty.call(value, k)) {  
  136.                         v = str(k, value);  
  137.                         if (v) {  
  138.                             partial.push(quote(k) + (gap ? ': ' : ':') + v);  
  139.                         }  
  140.                     }  
  141.                 }  
  142.             }  
  143.   
  144.   
  145.             v = partial.length === 0  
  146.                 ? '{}'  
  147.                 : gap  
  148.                 ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'  
  149.                 : '{' + partial.join(',') + '}';  
  150.             gap = mind;  
  151.             return v;  
  152.         }  
  153.     }  
  154.   
  155.   
  156.     if (typeof JSON.stringify !== 'function') {  
  157.         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;  
  158.         meta = {    // table of character substitutions  
  159.             '\b': '\\b',  
  160.             '\t': '\\t',  
  161.             '\n': '\\n',  
  162.             '\f': '\\f',  
  163.             '\r': '\\r',  
  164.             '"' : '\\"',  
  165.             '\\': '\\\\'  
  166.         };  
  167.         JSON.stringify = function (value, replacer, space) {  
  168.   
  169.   
  170.             var i;  
  171.             gap = '';  
  172.             indent = '';  
  173.   
  174.   
  175.             if (typeof space === 'number') {  
  176.                 for (i = 0; i < space; i += 1) {  
  177.                     indent += ' ';  
  178.                 }  
  179.   
  180.   
  181.             } else if (typeof space === 'string') {  
  182.                 indent = space;  
  183.             }  
  184.   
  185.   
  186.             rep = replacer;  
  187.             if (replacer && typeof replacer !== 'function' &&  
  188.                     (typeof replacer !== 'object' ||  
  189.                     typeof replacer.length !== 'number')) {  
  190.                 throw new Error('JSON.stringify');  
  191.             }  
  192.   
  193.   
  194.             return str('', {'': value});  
  195.         };  
  196.     }  
  197.   
  198.   
  199.   
  200.     if (typeof JSON.parse !== 'function') {  
  201.         cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;  
  202.         JSON.parse = function (text, reviver) {  
  203.   
  204.   
  205.   
  206.             var j;  
  207.   
  208.             function walk(holder, key) {  
  209.   
  210.   
  211.                 var k, v, value = holder[key];  
  212.                 if (value && typeof value === 'object') {  
  213.                     for (k in value) {  
  214.                         if (Object.prototype.hasOwnProperty.call(value, k)) {  
  215.                             v = walk(value, k);  
  216.                             if (v !== undefined) {  
  217.                                 value[k] = v;  
  218.                             } else {  
  219.                                 delete value[k];  
  220.                             }  
  221.                         }  
  222.                     }  
  223.                 }  
  224.                 return reviver.call(holder, key, value);  
  225.             }  
  226.   
  227.   
  228.   
  229.             text = String(text);  
  230.             cx.lastIndex = 0;  
  231.             if (cx.test(text)) {  
  232.                 text = text.replace(cx, function (a) {  
  233.                     return '\\u' +  
  234.                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);  
  235.                 });  
  236.             }  
  237.   
  238.   
  239.             if (/^[\],:{}\s]*$/  
  240.                     .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')  
  241.                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')  
  242.                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {  
  243.   
  244.   
  245.   
  246.                 j = eval('(' + text + ')');  
  247.   
  248.   
  249.   
  250.                 return typeof reviver === 'function'  
  251.                     ? walk({'': j}, '')  
  252.                     : j;  
  253.             }  
  254.   
  255.   
  256.             throw new SyntaxError('JSON.parse');  
  257.         };  
  258.     }  
  259. }());  

 

 

 

json2.min.js

 

[javascript] view plain copy

  1. "object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(a){return 10>a?"0"+a:a}function quote(a){return escapable.lastIndex=0,escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return"string"==typeof b?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function str(a,b){var c,d,e,f,h,g=gap,i=b[a];switch(i&&"object"==typeof i&&"function"==typeof i.toJSON&&(i=i.toJSON(a)),"function"==typeof rep&&(i=rep.call(b,a,i)),typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i)return"null";if(gap+=indent,h=[],"[object Array]"===Object.prototype.toString.apply(i)){for(f=i.length,c=0;f>c;c+=1)h[c]=str(c,i)||"null";return e=0===h.length?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]",gap=g,e}if(rep&&"object"==typeof rep)for(f=rep.length,c=0;f>c;c+=1)"string"==typeof rep[c]&&(d=rep[c],e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));else for(d in i)Object.prototype.hasOwnProperty.call(i,d)&&(e=str(d,i),e&&h.push(quote(d)+(gap?": ":":")+e));return e=0===h.length?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}",gap=g,e}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var cx,escapable,gap,indent,meta,rep;"function"!=typeof JSON.stringify&&(escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(a,b,c){var d;if(gap="",indent="","number"==typeof c)for(d=0;c>d;d+=1)indent+=" ";else"string"==typeof c&&(indent=c);if(rep=b,b&&"function"!=typeof b&&("object"!=typeof b||"number"!=typeof b.length))throw new Error("JSON.stringify");return str("",{"":a})}),"function"!=typeof JSON.parse&&(cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&"object"==typeof e)for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),void 0!==d?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}();  


 

 

在HTML代码中我们也可以使用以下来代码节约流量(IE7+及其它浏览器不加载json2.js)

<!--[if lt IE 8 ]><srcipt src="json2.js"></script><![endif]-->

转载于:https://my.oschina.net/u/2371743/blog/832277

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值