在前端開發裡,JSON 幾乎是資料交換的共通語言。JavaScript 內建的 JSON.stringify() 負責「序列化」,把物件變成字串;JSON.parse() 負責「反序列化」,把字串還原成物件;而 toJSON() 則是物件自訂序列化結果的介入點。以下把三者一起梳理清楚。
語法如下:
JSON.stringify(value [, replacer] [, space])
value(必填):要轉換的 JavaScript 值,通常是物件或陣列。
replacer(選填):可以是函式或陣列,用來過濾或改寫結果。
replacer 是函式,序列化時會針對每個成員呼叫它,並傳入「鍵」與「值」,最後採用函式的回傳值取代原始值;若回傳 undefined,該成員會被排除。根物件對應的鍵是空字串 ""。replacer 是陣列,則只有名稱出現在該陣列中的成員會被轉換,且輸出順序依照陣列中鍵的排列順序。當 value 本身也是陣列時,replacer 陣列會被忽略。space(選填):用來加入縮排、空白與換行,讓輸出的 JSON 文字更易讀。
"\t")時,每一層以該字串的內容縮排;若字串長度超過 10 個字元,只取前 10 個字元。序列化過程的優先順序是固定的:
value 具有 toJSON 方法,先呼叫它取得返回值;沒有則直接使用原始值。replacer,再以它的回傳值取代上一步的結果。space 參數補上縮排與換行,產出最終的 JSON 文字。另外要注意:不具備 JSON 表示形式的值(例如 undefined)不會被轉換。若它出現在物件中,該屬性會被丟棄;若出現在陣列中,則會被替換成 null。
下列程式只保留 surname 與 phone,刻意省略 firstname:
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
var memberfilter = new Array();
memberfilter[0] = "surname";
memberfilter[1] = "phone";
var jsonText = JSON.stringify(contact, memberfilter, "\t");
document.write(jsonText);
// Output:
// { "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] }
語法:
objectname.toJSON()
objectname 為必填參數,代表要進行 JSON 序列化的物件。
toJSON 是 Date 物件與生俱來的內建模組,呼叫後會回傳以 UTC 時區表示的 ISO 格式日期字串(以 Z 結尾)。除了日期之外,你也可以替自訂物件掛上 toJSON,藉此完全掌控序列化的輸出內容。
以下範例把 contact 物件中所有字串成員轉為大寫,並在 JSON.stringify() 執行時自動生效:
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
contact.toJSON = function(key)
{
var replacement = new Object();
for (var val in this)
{
if (typeof (this[val]) === 'string')
replacement[val] = this[val].toUpperCase();
else
replacement[val] = this[val]
}
return replacement;
};
var jsonText = JSON.stringify(contact);
/* jsonText 的值為:
'{"firstname":"JESPER","surname":"AABERG","phone":["555-0100","555-0120"]}'
*/
語法:
JSON.parse(text [, reviver])
text(必填):合法的 JSON 字串。
reviver(選填):轉換結果用的函式,會針對物件的每個成員被呼叫。若成員內含巢狀物件,會先處理巢狀物件、再處理父物件。對每個成員而言:
null 或 undefined → 該成員被刪除。var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
// Output: Aaberg, Jesper
先把陣列序列化成字串,再把字串還原為陣列,這是最常見的往返用法:
var arr = ["a", "b", "c"];
var str = JSON.stringify(arr);
document.write(str);
document.write("<br/>");
var newArr = JSON.parse(str);
while (newArr.length > 0) {
document.write(newArr.pop() + "<br/>");
}
// Output:
// ["a","b","c"]
// c
// b
// a
把三者的關係記成一句話:toJSON 決定「怎麼序列化」,stringify 負責「序列化並可再加工」,parse 負責「還原」。掌握 replacer、space 與 reviver 這三個進階參數,就能處理大多數資料轉換與格式化場景。