JSON.stringify() 方法将一個 JavaScript 對象或值轉換為 JSON 字元串,如果指定了一個 replacer 函數,則可以選擇性地替換值,或者指定的 replacer 是數組,則可選擇性地僅包含數組指定的屬性。
文法如下:
JSON.stringify(value[, replacer [, space]])
- 第一個參數 value:将要序列化成 一個 JSON 字元串的值。
- 第二個參數 replacer:可選參數,如果該參數是一個函數,則在序列化過程中,被序列化的值的每個屬性都會經過該函數的轉換和處理;如果該參數是一個數組,則隻有包含在這個數組中的屬性名才會被序列化到最終的 JSON 字元串中;如果該參數為 null 或者未提供,則對象所有的屬性都會被序列化。
- 第三個參數 space:可選參數,指定縮進用的空白字元串,用于美化輸出(pretty-print);如果參數是個數字,它代表有多少的空格;上限為 10。該值若小于 1,則意味着沒有空格;如果該參數為字元串(當字元串長度超過 10 個字母,取其前 10 個字母),該字元串将被作為空格;如果該參數沒有提供(或者為 null),将沒有空格。
第二個參數replacer為數組
是的,JSON.stringify() 函數可以有第二個參數,它是要在控制台中列印的對象的鍵數組。下面來看看示例:
const arrayData = [
{
id: "0001",
type: "donut",
name: "Cake",
ppu: 0.55,
batters: {
batter: [
{ id: "1001", type: "Regular" },
{ id: "1002", type: "Chocolate" },
{ id: "1003", type: "Blueberry" },
{ id: "1004", type: "Devil’s Food" },
],
},
topping: [
{ id: "5001", type: "None" },
{ id: "5002", type: "Glazed" },
{ id: "5005", type: "Sugar" },
{ id: "5007", type: "Powdered Sugar" },
{ id: "5006", type: "Chocolate with Sprinkles" },
{ id: "5003", type: "Chocolate" },
{ id: "5004", type: "Maple" },
],
},
];
console.log(JSON.stringify(arrayData, ["name"])); // [{"name":"Cake"}]
可以通過在第二個參數中将其作為數組傳遞僅需要列印的鍵,而不需要列印整個 JSON 對象。
第二個參數replacer為函數
還可以将第二個參數作為函數傳遞,根據函數中編寫的邏輯評估每個鍵值對。如果傳回 undefined 鍵值對将不會列印。請看下面示例:
const user = {
name: "DevPoint",
age: 35,
};
const result = JSON.stringify(user, (key, value) =>
typeof value === "string" ? undefined : value
);
console.log(result); // {"age":35}
上述代碼的輸出,可以用來過濾 JSON 資料的屬性值。
第三個參數為 Number
第三個參數控制最終字元串中的間距。如果參數是一個數字,則字元串化中的每個級别都将縮進此數量的空格字元。
const user = {
name: "DevPoint",
age: 35,
address: {
city: "Shenzhen",
},
};
console.log(JSON.stringify(user, null, 4));
輸出列印的字元串格式如下:
{
"name": "DevPoint",
"age": 35,
"address": {
"city": "Shenzhen"
}
}
第三個參數為 String
如果第三個參數是一個字元串,它将被用來代替上面顯示的空格字元。
const user = {
name: "DevPoint",
age: 35,
address: {
city: "Shenzhen",
},
};
console.log(JSON.stringify(user, null, "|---"));
輸出列印的字元串格式如下:
{
|---"name": "DevPoint",
|---"age": 35,
|---"address": {
|---|---"city": "Shenzhen"
|---}
}
toJSON 方法
有一個名為 toJSON 的方法,它可以是任何對象的一部分作為其屬性。JSON.stringify 傳回此函數的結果并将其字元串化,而不是将整個對象轉換為字元串。
//Initialize a User object
const user = {
name: "DevPoint",
city: "Shenzhen",
toJSON() {
return `姓名:${this.name},所在城市:${this.city}`;
},
};
console.log(JSON.stringify(user)); // "姓名:DevPoint,所在城市:Shenzhen"
- EOF -