导航栏: 首页 评论列表

Object / Array to JSON

默认分类 2012-05-13 19:19:41

调试代码时,常常需要将数据读出,这个小工具或许能帮上忙.

  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.   
  4. <head>  
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  6. <title>Untitled 1</title>  
  7. <script type="text/javascript">  
  8. <!--  
  9.   
  10. function tojson(target) {  
  11.     var str = [],  
  12.         i,  
  13.         len;  
  14.     if (Object.prototype.toString.call(target)==='[object Array]') {  
  15.         for (i=0,len=target.length; i<len; i++) {  
  16.             str.push(tojson(target[i]));  
  17.         }  
  18.         str = '['+str.join(',')+']';  
  19.     }  
  20.     else if (!!target  && (typeof target == 'object' || typeof target == 'function')) {  
  21.         for (i in target) {  
  22.             if (!i && !target[i]) {  
  23.                 continue;  
  24.             }  
  25.             else {  
  26.                 str.push('"'+String(i).toString().replace(/\"/g,'\\"')+'":'+tojson(target[i]));  
  27.             }  
  28.         }  
  29.         str = '{'+str.join(',')+'}';  
  30.     }  
  31.     else if ( target === undefined){  
  32.         str = 'undefined';  
  33.     }  
  34.     else if ( target === null){  
  35.         str = 'null';  
  36.     }  
  37.     else {  
  38.         str = '"'+String(target).toString().replace(/\"/g,'\\"')+'"';  
  39.     }  
  40.     return str;  
  41. }  
  42.   
  43. function doit(){  
  44.     //todo  
  45.     alert(tojson({'a':[{'"':123,'c':undefined}]}));  
  46. }  
  47.   
  48. //-->  
  49. </script>  
  50. </head>  
  51.   
  52. <body><button type="button" onclick="doit()">doit</button>  
  53.   
  54. </body>  
  55.   
  56. </html>  


>> 留言评论