js 对象和Json的转换,js及深度复制

Java代码  收藏代码
  1. Object.prototype.deep_clone = function(){  
  2.     eval("var tmp = " + this.toJSON());  
  3.     return tmp;  
  4. }  
  5. Object.prototype.toJSON = function(){  
  6.     var json = [];  
  7.     for(var i in this){  
  8.         if(!this.hasOwnProperty(i)) continue;  
  9.         //if(typeof this[i] == "function") continue;  
  10.         json.push(  
  11.             i.toJSON() + " : " +  
  12.             ((this[i] != null) ? this[i].toJSON() : "null")  
  13.         )  
  14.     }  
  15.     return "{\n " + json.join(",\n ") + "\n}";  
  16. }  
  17. Array.prototype.toJSON = function(){  
  18.     for(var i=0,json=[];i<this.length;i++)  
  19.         json[i] = (this[i] != null) ? this[i].toJSON() : "null";  
  20.     return "["+json.join(", ")+"]"  
  21. }  
  22.   
  23. String.prototype.toJSON = function(){  
  24.     return '"' +  
  25.         this.replace(/(\\|\")/g,"\\$1")  
  26.         .replace(/\n|\r|\t/g,function(){  
  27.             var a = arguments[0];  
  28.             return  (a == '\n') ? '\\n':  
  29.                     (a == '\r') ? '\\r':  
  30.                     (a == '\t') ? '\\t'""  
  31.         }) +  
  32.         '"'  
  33. }  
  34. Boolean.prototype.toJSON = function(){return this}  
  35. Function.prototype.toJSON = function(){return this}  
  36. Number.prototype.toJSON = function(){return this}  
  37. RegExp.prototype.toJSON = function(){return this}  
  38.   
  39. // strict but slow  
  40. String.prototype.toJSON = function(){  
  41.     var tmp = this.split("");  
  42.     for(var i=0;i<tmp.length;i++){  
  43.         var c = tmp[i];  
  44.         (c >= ' ') ?  
  45.             (c == '\\') ? (tmp[i] = '\\\\'):  
  46.             (c == '"')  ? (tmp[i] = '\\"' ): 0 :  
  47.         (tmp[i] =   
  48.             (c == '\n') ? '\\n' :  
  49.             (c == '\r') ? '\\r' :  
  50.             (c == '\t') ? '\\t' :  
  51.             (c == '\b') ? '\\b' :  
  52.             (c == '\f') ? '\\f' :  
  53.             (c = c.charCodeAt(),('\\u00' + ((c>15)?1:0)+(c%16)))  
  54.         )  
  55.     }  
  56.     return '"' + tmp.join("") + '"';  
  57. }  




测试: 

Java代码  收藏代码
    1. var json = {  
    2.     str : "abcde",  
    3.     num : 6,  
    4.     reg : /foobar/i,  
    5.     array : [1,2,3,4,5],  
    6.     func : function(x,y){return x+y},  
    7.     obj : {a : "b"}  
    8. }.toJSON();  
    9.   
    10. alert(json);  
    11. // result  
    12. {  
    13.  "str" : "abcde",  
    14.  "num" : 6,  
    15.  "reg" : /foobar/i,  
    16.  "array" : [12345],  
    17.  "func" : function(x,y){return x+y},  
    18.  "obj" : {  
    19.  "a" : "b"  
    20. }  
    21. }  
posted @ 2012-09-19 08:51  楼上少年  阅读(438)  评论(0编辑  收藏  举报