Object / Array to JSON
默认分类 2012-05-13 19:19:41
调试代码时,常常需要将数据读出,这个小工具或许能帮上忙.
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
-
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Untitled 1</title>
- <script type="text/javascript">
- <!--
-
- function tojson(target) {
- var str = [],
- i,
- len;
- if (Object.prototype.toString.call(target)==='[object Array]') {
- for (i=0,len=target.length; i<len; i++) {
- str.push(tojson(target[i]));
- }
- str = '['+str.join(',')+']';
- }
- else if (!!target && (typeof target == 'object' || typeof target == 'function')) {
- for (i in target) {
- if (!i && !target[i]) {
- continue;
- }
- else {
- str.push('"'+String(i).toString().replace(/\"/g,'\\"')+'":'+tojson(target[i]));
- }
- }
- str = '{'+str.join(',')+'}';
- }
- else if ( target === undefined){
- str = 'undefined';
- }
- else if ( target === null){
- str = 'null';
- }
- else {
- str = '"'+String(target).toString().replace(/\"/g,'\\"')+'"';
- }
- return str;
- }
-
- function doit(){
-
- alert(tojson({'a':[{'"':123,'c':undefined}]}));
- }
-
-
- </script>
- </head>
-
- <body><button type="button" onclick="doit()">doit</button>
-
- </body>
-
- </html>
>>
留言评论