JSON-stringify-- 的 5 使用場景

JSON.stringify() 方法將一個 JavaScript 對象或值轉換爲 JSON 字符串,如果指定了一個 replacer 函數,則可以選擇性地替換值,或者指定的 replacer 是數組,則可選擇性地僅包含數組指定的屬性。

語法如下:

JSON.stringify(value[, replacer [, space]])

第二個參數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