DIV CSS 佈局教程網

用正則表達式格式化並高亮顯示 JSON 字串
編輯:關於JavaScript     

後端介面常回傳壓縮過的 JSON 字串,可讀性極差。如果能有個方法把它格式化並加上語法高亮,除錯會輕鬆很多。本文示範如何只用正則表達式完成這件事。

第一步:正規化輸入

先確保手上是標準的 JSON 字串。若是物件就用 JSON.stringify 轉成字串;若是字串,先 parse 再 stringify 一遍,藉此把不規範的寫法(單引號、多餘逗號等能處理的部分)導正。

if (typeof json !== 'string') {
  json = JSON.stringify(json);
} else {
  json = JSON.parse(json);
  json = JSON.stringify(json);
}

第二步:插入換行標記

在幾個關鍵位置加上換行,作為後續切分的依據。這裡用 \r\n,在命令列環境下顯示效果較好。

// 大括號前後
json = json.replace(/([\{\}])/g, '\r\n$1\r\n');
// 中括號前後
json = json.replace(/([\[\]])/g, '\r\n$1\r\n');
// 逗號後面
json = json.replace(/(\,)/g, '$1\r\n');

第三步:清理多餘換行

上一步會產生連續的空行,也要把逗號前面的換行去掉,避免切分出空字串而多跑一次迴圈。最後在冒號後補一個空格,視覺上更舒適。

json = json.replace(/(\r\n\r\n)/g, '\r\n');  // 去掉多餘空行
json = json.replace(/\r\n\,/g, ',');         // 逗號前的換行移除
json = json.replace(/\:/g, ': ');           // 冒號後加空格

第四步:逐行處理縮進

用換行切分成陣列,對每一行套用縮進邏輯:

$.each(json.split('\r\n'), function (index, node) {
  // 在這裡處理每一行
});

縮進規則很簡單:遇到 { 或 [ 結尾時縮進等級加一;遇到 } 或 ] 時減一;其餘不變。

if (node.match(/\{$/) || node.match(/\[$/)) {
  indent = 1;
} else if (node.match(/\}/) || node.match(/\]/)) {
  if (pad !== 0) { pad -= 1; }
} else {
  indent = 0;
}

注意關閉括號那一行要先減一層再輸出,這樣 } 才會與對應的開頭對齊。

第五步:加上語法高亮

先定義幾個 CSS class:

.ObjectBrace  { color: #00AA00; font-weight: bold; }
.ArrayBrace   { color: #0033FF; font-weight: bold; }
.PropertyName { color: #CC0000; font-weight: bold; }
.String       { color: #007777; }
.Number       { color: #AA00AA; }
.Comma        { color: #000000; font-weight: bold; }

然後用正則替換包上 span:

node = node.replace(/([\{\}])/g, "<span class='ObjectBrace'>$1</span>");
node = node.replace(/([\[\]])/g, "<span class='ArrayBrace'>$1</span>");
node = node.replace(/(\".*\")(\:)(.*)(\,)?/g, "<span class='PropertyName'>$1</span>$2$3$4");
node = node.replace(/\"([^"]*)\"(\,)?$/g, "<span class='String'>\"$1\"</span><span class='Comma'>$2</span>");
node = node.replace(/(-?\d+)(\,)?$/g, "<span class='Number'>$1</span><span class='Comma'>$2</span>");

完整程式碼

<script>
var APP = function () {
  var format = function (json) {
    var reg = null, result = '';
    var pad = 0, PADDING = ' ';

    if (typeof json !== 'string') {
      json = JSON.stringify(json);
    } else {
      json = JSON.parse(json);
      json = JSON.stringify(json);
    }

    json = json.replace(/([\{\}])/g, '\r\n$1\r\n');
    json = json.replace(/([\[\]])/g, '\r\n$1\r\n');
    json = json.replace(/(\,)/g, '$1\r\n');
    json = json.replace(/(\r\n\r\n)/g, '\r\n');
    json = json.replace(/\r\n\,/g, ',');
    json = json.replace(/\:/g, ': ');

    $.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; }

      node = node.replace(/([\{\}])/g, "<span class='ObjectBrace'>$1</span>");
      node = node.replace(/([\[\]])/g, "<span class='ArrayBrace'>$1</span>");
      node = node.replace(/(\".*\")(\:)(.*)(\,)?/g, "<span class='PropertyName'>$1</span>$2$3$4");
      node = node.replace(/\"([^"]*)\"(\,)?$/g, "<span class='String'>\"$1\"</span><span class='Comma'>$2</span>");
      node = node.replace(/(-?\d+)(\,)?$/g, "<span class='Number'>$1</span><span class='Comma'>$2</span>");

      result += padding + node + '<br>';
      pad += indent;
    });

    return result;
  };

  return { "format": format };
}();

使用時呼叫 APP.format(jsonstr),把結果輸出到 <pre> 標籤中即可。

補充:用正則修改 JSON 中的某個欄位值

aa = aa.replace(/"ccfsID":"[0-9]*"/, '"ccfsID":"' + id1 + '"');

其中 aa 是 JSON 字串,例如:

{"items":[{"dishprice":30,"ccfsID":"","order.item.id":1,"zuofaid":"","zuofajiajia":0,"isTaoCan":false,"num":1,"price":30,"name":"","ID":"00000001","lsdishID":"","zuofaname":"","tzs":"","addTime":"2013-05-14"}],"deskId":"00000008"}

實務建議

用正則做 JSON 格式化是很好的練習,但要清楚它的界線:正則表達式無法真正解析巢狀結構。上述程式碼在遇到值裡含有括號、逗號或換行的字串時就會出錯,例如 {"text":"a,b"} 會被錯誤斷行。

正式環境中請直接用成熟方案:

  • JSON.stringify(obj, null, 2) 就能完成格式化,內建支援,一行搞定。
  • 高亮可用 highlight.js、prism.js 這類專門的語法高亮庫,它們有正確的 tokenizer,能處理各種邊界情況。
  • 若只是想快速檢視,瀏覽器 DevTools 的 Console 本身就會自動格式化並折疊物件。

正則在「已知格式固定、結構單純」的替換場景(例如上面補充的那個例子)中仍然非常實用,只是不該拿它當 JSON parser 用。

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