把 JSON 物件或 JSON 字串做美化排版,方便在網頁上呈現,是除錯與 API 除錯工具中很實用的小功能。以下是一個可直接使用的格式化函式。
var formatJson = function (json, options) {
var reg = null, formatted = '', pad = 0, PADDING = '';
// PADDING 可改為 '\t' 或其他數量的空白
options = options || {};
// 冒號後是否允許換行(當冒號後緊接 { 或 [ 時)
options.newlineAfterColonIfBeforeBraceOrBracket =
(options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
// 冒號後是否加一個空格
options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
// 先正規化輸入:是物件就 stringify,是字串就 parse 後再 stringify(去除多餘空白)
if (typeof json !== 'string') {
json = JSON.stringify(json);
} else {
json = JSON.parse(json);
json = JSON.stringify(json);
}
// 在大括號前後加換行
reg = /([\{\}])/g;
json = json.replace(reg, '\r\n$1\r\n');
// 在方括號前後加換行
reg = /([\[\]])/g;
json = json.replace(reg, '\r\n$1\r\n');
// 逗號後加換行
reg = /(\,)/g;
json = json.replace(reg, '$1\r\n');
// 移除多餘的空行
reg = /(\r\n\r\n)/g;
json = json.replace(reg, '\r\n');
// 移除逗號前的換行
reg = /\r\n\,/g;
json = json.replace(reg, ',');
// 可選的額外調整
if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
reg = /\:\r\n\{/g;
json = json.replace(reg, ':{');
reg = /\:\r\n\[/g;
json = json.replace(reg, ':[');
}
if (options.spaceAfterColon) {
reg = /\:/g;
json = json.replace(reg, ': ');
}
// 依縮排層級逐行加上縮排
$.each(json.split('\r\n'), function (index, node) {
var i = 0, indent = 0, padding = '';
if (node.match(/\{$/) || node.match(/\[$/)) {
indent = 1; // 開頭的括號,下一行要縮排
} else if (node.match(/\}/) || node.match(/\]/)) {
if (pad !== 0) { pad -= 1; } // 結尾的括號,先退一層
} else {
indent = 0;
}
for (i = 0; i < pad; i++) { padding += PADDING; }
formatted += padding + node + '\r\n';
pad += indent;
});
return formatted;
};
整個演算法分兩階段:先用一串正則把 JSON 拆成「一行一個 token」的形式,再逐行判斷縮排深度並組裝結果。縮排的關鍵判斷是:當一行以 { 或 [ 結尾時,下一層要加一級縮排;當一行本身就是 } 或 ] 時,這行要先退一級再輸出。
這個做法有兩個實務上的問題值得注意。
第一,正則正規化會誤傷字串內容。如果某個字串值裡含有 {、, 或 :,例如 {"msg":"hello, {world}"},上面的正則會把字串內部的字元也當成結構符號處理,導致輸出的 JSON 排版錯亂(內容本身沒壞,但已不再是合法可讀的結構)。這是所有「用正則處理 JSON」方案的共同弱點。
第二,範例中 PADDING = '',所以實際上不會有縮排效果,要自己填入空白或 \t;而 $.each 意味著它依賴 jQuery。
因此,如果目的只是「把 JSON 印得漂亮」,原生 API 已經足夠:
var pretty = JSON.stringify(obj, null, 2); // 2 個空白縮排 var prettyTab = JSON.stringify(obj, null, "\t"); // 用 tab 縮排
若要進一步「上色」,則把 token 序列化後用正則加上 <span> 包裹(記得先轉義 <、>、& 以防 XSS),或直接改用 <pre> 搭配 CSS。瀏覽器內建的工具與 JSON 線上格式化工具也都已基於 JSON.stringify 實作,比自行以正則解析可靠得多。