JSON-stringify-- 的 5 使用場景
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"
作者: 天行無忌
https://juejin.cn/post/7191712569394987065
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/UYKVSxReYk24WMiktvf8YA