• JavaScript如何将对象或值转换为 JSON 字符串?
  • 发布于 2个月前
  • 182 热度
    0 评论
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() 函数可以有第二个参数,它是要在控制台中打印的对象的键数组。下面来看看示例:
// 堆代码 duidaima.com
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"

用户评论