js数据类型的转换

string转其它

==================================
string转json
var json = eval('('+ string +')');

string转arr
var arr = string.split(",");

string转number
parseInt()

 

 

 

js JSON与String互转换

============================

 1 function jsonToString (obj){   
 2         var THIS = this;    
 3         switch(typeof(obj)){   
 4             case 'string':   
 5                 return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';   
 6             case 'array':   
 7                 return '[' + obj.map(THIS.jsonToString).join(',') + ']';   
 8             case 'object':   
 9                  if(obj instanceof Array){   
10                     var strArr = [];   
11                     var len = obj.length;   
12                     for(var i=0; i<len; i++){   
13                         strArr.push(THIS.jsonToString(obj[i]));   
14                     }   
15                     return '[' + strArr.join(',') + ']';   
16                 }else if(obj==null){   
17                     return 'null';   
18   
19                 }else{   
20                     var string = [];   
21                     for (var property in obj) string.push(THIS.jsonToString(property) + ':' + THIS.jsonToString(obj[property]));   
22                     return '{' + string.join(',') + '}';   
23                 }   
24             case 'number':   
25                 return obj;   
26             case false:   
27                 return obj;   
28         }   
29     }
30  
31 function stringToJSON(obj){   
32         return eval_r('(' + obj + ')');   
33 }

 

posted @ 2013-03-26 19:50  dtdxrk  阅读(245)  评论(0编辑  收藏  举报