DIV CSS 佈局教程網

用 jQuery 格式化輸出 JSON 與轉為陣列
編輯:JavaScript綜合知識     

除錯時想把 JSON 結構印成人類看得懂的樣子,或者需要在物件與陣列之間轉換,這組 jQuery 擴充提供了三個工具函式,分別負責「印出並回傳字串」、「只回傳字串」與「轉成陣列」。

外掛主體

/*
 * print the json object
 *
 * $("selector").print_r_json(json, opts) : 回傳格式化字串(並輸出)
 * $.sprint_r_json(json)                  : 只回傳字串
 * $.print_r_json(json)                   : 回傳格式化字串並直接輸出
 *
 * 三種使用方式:
 * $("selector").print_r_json({...}, { if_print: true, return_array: true });
 * document.write($.sprint_r_json({...}));
 * $.print_r_json({...});
 */
$.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) {
    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>[' + 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>[' + 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:邏輯相同但不輸出,只組字串回傳,可安全地插入任何位置。
  • $.json_to_array:把物件的每個鍵值搬進陣列的對應索引,遞迴處理巢狀結構。

縮排是靠 margin-left:25px 逐層遞加做出來的,這也是它視覺上像 PHP print_r 的原因。

使用時該注意的三件事

document.write 的時機限制

頁面載入完成後呼叫 document.write 會清空整個文件。除錯時請務必用 sprint_r_json 搭配 console.log,或把結果塞進指定元素。

innerHTML 的 XSS 風險

把 JSON 值直接串進 HTML 字串,若內容含有使用者輸入的 <script> 就可能被執行。檢視資料時,用 <pre> 搭配 textContent 才是安全做法:

console.log(JSON.stringify(data, null, 2));

現代瀏覽器內建的這一行,就能完成格式化輸出,不必任何外掛。

json_to_array 的語意風險

用物件的鍵當陣列索引,若鍵不是連續整數會產生稀疏陣列;而 JSON 物件的鍵實際上是字串,轉成陣列後 length 的意義並不明確。若目的只是遍歷,Object.keys(obj).map(...) 才是語意清晰的寫法。

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