DIV CSS 佈局教程網

把 JSON 轉成可讀格式或陣列:三個 jQuery 工具函式
編輯:JQuery特效代碼     

除錯時經常需要把一個 JSON 物件印出來看,但直接丟給 console.log 或 document.write 往往只得到一團 [object Object]。這份程式碼示範了另一條路:遞迴走訪物件,把它格式化成一層層縮排的 HTML,同時提供轉成陣列與純取字串兩種變體。

/*print the json object
 *
 *$("selector").print_r_json(json,opts) : return formatted string (and print)
 *sprint_r_json : just return the string;
 *print_r_json : return the formatted string and print json data
 *contribute 明河
 *
 *auth iorichina
 *
 *example: 
 *3 ways to use it
 *<script language="javascript">
 *$("selector").print_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"},{if_print:true,return_array:true});
 *document.write($.sprint_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"}));
 *$.print_r_json({"a":"aa","d":{"ef":{"a":"d","d":["a","b"]},"ed":"dd"},"g":"g"});
 *</script>
 *
 */
$.fn.print_r_json = function(json,options){
   if(typeof(json)!="object") return false;
   var opts = $.extend({},$.fn.print_r_json.defaults,options);
   var data = '';
   if(opts.if_print)
   {
     data = $.sprint_r_json(json)
     $(this).html('<div style="font-weight:bold">'+(opts.return_array?'Array':'JSON-DATA')+'</div>'+data);
   }
   if(opts.array)
   {
     return $.json_to_array(json);
   }
   return data;
};
$.fn.print_r_json.defaults = 
{
   if_print : false,//if print or just return formatted string
   return_array : true //return an Array 
};
$.extend({
   print_r_json : function(json)
   {
     if(typeof(json)=="object")
     {
         var text='<div style="font-weight:bold;">{</div><div style="margin-left:25px;">';
         document.write('<div style="font-weight:bold;">{</div><div style="margin-left:25px;">');
         for(var p in json)
         {
              if(typeof(json[p])=="object")
              {
                  document.write('<div>["'+p+'"] => ');
                  text+='<div>["'+p+'"] => '+$.print_r_json(json[p])+'</div>';
                  document.write('</div>');
              }
              else
              {
                  text+='<div>['+((/^\d+$/).test(p)?p:('"'+p+'"'))+'] => "'+json[p]+'"</div>';
                  document.write('<div>['+p+'] => '+json[p]+'</div>');
              }
         } 
             text+='</div><div style="font-weight:bold;">}</div>';
             document.write('</div><div style="font-weight:bold;">}</div>');
             return (text);
         }
         else
         {
             document.write(json);
             return (json);
         }
   },
   sprint_r_json : function(json)
   {
     if(typeof(json)=="object")
     {
         var text = '<div style="font-weight:bold;">{</div><div style="margin-left:25px;">';
         for(var p in json)
         {
              if(typeof(json[p])=="object")
              {
                  text += '<div>["'+p+'"] => '+$.sprint_r_json(json[p])+'</div>';
              }
              else
              {
                  text += '<div>['+((/^\d+$/).test(p)?p:('"'+p+'"'))+'] => "'+json[p]+'"</div>';
              }
         } 
         text += '</div><div style="font-weight:bold;">}</div>';
         return (text);
     }
     else
     {
         return (json);
     }
   },
   json_to_array : function(json)
   {
     if(typeof(json)=="object")
     {
         var text = new Array();
         for(var p in json)
         {
              if(typeof(json[p])=="object")
              {
                  text[p] = $.json_to_array(json[p]);
              }
              else
              {
                  text[p] = json[p];
              }
         }
         return (text);
     }
     else
     {
         return (json);
     }
   }
});

三個函式怎麼分工

$.print_r_json 一邊組字串一邊用 document.write 直接輸出,適合快速在頁面上看一眼;$.sprint_r_json 邏輯幾乎相同,但只回傳字串不輸出,命名顯然是向 PHP 的 print_r/sprint_r 致敬;$.json_to_array 則是把物件的每一層都攤平成陣列形式。三者共同的骨架都是同一件事:遞迴——遇到值仍是物件就往下呼叫自己,遇到基本型別就停下來輸出。

挂在 $.fn 上的 print_r_json 是給選擇器用的版本,透過 if_print 決定是否寫入元素、return_array 決定標題顯示 Array 還是 JSON-DATA,並用 $.extend 合併預設值,是相當典型的插件寫法。

今天該怎麼做

這個思路在當年很實用,但現在有更省事的方式:JSON.stringify(obj, null, 2) 一行就能得到縮排兩格的可讀字串,丟進 <pre> 即可閱讀;瀏覽器內建開發者工具也能展開任意物件層級。若目的是「把物件攤平成陣列」,Object.keys(obj) 或 Object.entries(obj) 會比手寫遞迴清楚得多。

不過這份程式碼仍有可借鏡之處:它把「取得資料」與「輸出資料」拆成不同函式,讓同一套遞迴邏輯能被三種情境重用,這種分工方式在設計自己的工具函式時值得參考。另外提醒一點,用字串拼接產生 HTML 時若 JSON 內容來自使用者輸入,務必先做轉義,否則會有 XSS 風險。

希望本文所述對你的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved