開發過程中常需在頁面上直接檢視 JSON 結構。本文提供一組 jQuery 擴展方法:$.print_r_json、$.sprint_r_json、$.json_to_array,可將 JSON 物件格式化為 HTML 輸出、回傳字串、或轉為原生 JS 陣列/物件。
| 方法 | 用途 | 回傳值 |
|---|---|---|
$(selector).print_r_json(json, opts) | 在指定容器輸出格式化 HTML,可選是否同時回傳陣列 | 格式化字串或陣列 |
$.print_r_json(json) | 直接 document.write 輸出格式化 HTML | 格式化字串 |
$.sprint_r_json(json) | 僅回傳格式化 HTML 字串,不輸出 | 格式化字串 |
$.json_to_array(json) | 遞迴轉換 JSON 為原生陣列/物件 | Array/Object |
$.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, return_array: true };
$.extend({
print_r_json: function(json) { /* 遞迴產生巢狀 HTML,document.write 輸出 */ },
sprint_r_json: function(json) { /* 遞迴產生巢狀 HTML,回傳字串 */ },
json_to_array: function(json) { /* 遞迴轉換為陣列/物件 */ }
});
// 1. 在 #debug 容器輸出並取得陣列
var arr = $("#debug").print_r_json({a:"aa", d:{ef:{a:"d", d:["a","b"]}, ed:"dd"}, g:"g"}, {if_print:true, return_array:true});
// 2. 直接 document.write 輸出
$.print_r_json({a:"aa", d:{ef:{a:"d", d:["a","b"]}, ed:"dd"}, g:"g"});
// 3. 僅取得格式化字串自行處理
var html = $.sprint_r_json({a:"aa", d:{ef:{a:"d", d:["a","b"]}, ed:"dd"}, g:"g"});
document.write(html);
document.write,僅適合開發除錯階段,正式環境請改用 console.log、console.dir 或開發者工具。/^d+$/ 應為 /^\d+$/(缺少反斜線),否則無法正確判斷數字鍵名。<、> 等字元會導致結構錯亂,建議加入 escapeHtml 處理。JSON.stringify + <pre>function prettyPrint(json) {
document.getElementById('debug').innerHTML = '<pre>' + JSON.stringify(json, null, 2) + '</pre>';
}