javascript对象转化成json字符串

代码:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5     <title>EQQ Proxy</title>
 6 </head>
 7 
 8 <body>
 9 <script language="javascript">
10 var obj = {
11     v1 : {
12         v11 : 'value1',
13         vl2 : 'value2'
14     }    ,
15     v2 : 'value3',
16     f1 : function(){
17         alert("hi");
18     }
19 }
20 
21 /**
22  * Converts the given data structure to a JSON string.
23  * Argument: arr - The data structure that will be converted to JSON
24  * Example:  var json_string = toJson(['e', {pluribus: 'unum'}]);
25  *
26  */
27 function toJson(arr) {
28     var parts = [];
29     var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
30 
31     for(var key in arr) {
32         var value = arr[key];
33         if(typeof value == "object") {
34             parts.push(toJson(value));
35         }else if(typeof value == "function"){
36                 value = value.toString()
37                              .replace(/(\n[\s|\t]*\r*\n)/g, '')
38                              .replace(/\n|\r|(\r\n)/g,'')
39                              .replace(/\s{2,}/,'')
40                              .replace(/"/,'\"');
41                 parts.push('\"' + value + '\"');
42         } else {
43             var str = "";
44             if(!is_list){
45                key = key.replace(/"/,'\"');
46                str = '\"' + key + '\":';
47             }
48 
49             //Custom handling for multiple data types
50             if(typeof value == "number"){//Numbers
51                  str += value;
52             }else if(value === false){//The booleans false
53                 str += 'false';
54             }else if(value === true){//The booleans true
55                 str += 'true';
56             }else{//string
57                 value = value.replace(/"/,'\"');
58                 str += '\"' + value + '\"';
59             }
60 
61             parts.push(str);
62         }
63     }
64     var json = parts.join(",");
65     if(is_list) return '[' + json + ']';//array
66     return '{' + json + '}';//object
67 }
68 
69 console.log(toJson(obj));
70 </script>
71 
72 </body>
73 </html>

 

 

posted @ 2010-09-29 13:05  wingle  阅读(403)  评论(0编辑  收藏  举报