JSON.stringify() 方法能将一个 JavaScript 对象或值转换成一个 JSON 字符串。
JSON.stringify() 是用于调试的最常见函数。但是它的作用是什么呢,难道我们不能使用 console.log() 来做同样的事情吗?让我们试一试:
//初始化一个 user 对象
const user = {
"name" : "Prateek Singh",
"age" : 26
}
console.log(user);
// 结果
// [object Object]
console.log() 没有帮助我们打印出期望的结果。它输出 [object Object],因为从对象到字符串的默认转换是 [object Object]。因此,我们使用 JSON.stringify() 首先将对象转换成字符串,然后在控制台中打印,如下所示:
const user = {
"name" : "Prateek Singh",
"age" : 26
}
console.log(JSON.stringify(user));
// 结果
// "{ "name" : "Prateek Singh", "age" : 26 }"
stringify 函数也可以有第二个参数。它是要在控制台中打印的对象的键数组。假设我们有一个对象 product 并且我们想知道 product 的 name 属性值。当我们将其打印出来:
console.log(JSON.stringify(product));
它会输出下面的结果:
{
"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"
}
]
}
在日志中很难找到 name 键,因为控制台上显示了很多没用的信息。当对象变大时,查找属性的难度增加。 stringify 函数的第二个参数这时就有用了。让我们重写代码并查看结果:
console.log(JSON.stringify(product,['name' ]);
// 结果
{"name" : "Cake"}
与打印整个 JSON 对象不同,我们可以在第二个参数中将所需的键作为数组传递,从而只打印所需的属性。
stringify 还可以传入函数作为第二个参数。它根据函数中写入的逻辑来计算每个键值对。如果返回 undefined,则不会打印键值对。请看下面的示例:
const user = {
"name" : "Prateek Singh",
"age" : 26
}
JSON.stringify(user, (key, value) => {
if (typeof value === 'string'){
return undefined;
}
return value;
});
//结果:
{"age":26}
只有 age 被打印出来,因为函数判断 typeOf 为 String 的值返回 undefined。
stringify 第三个参数控制最后一个字符串的间距。如果参数是一个数字,则字符串化中的每个级别都将缩进这个数量的空格字符:
// 注意:为了达到理解的目的,使用 '--' 替代了空格
JSON.stringify(user, null, 2);
//{
//--"name": "Prateek Singh",
//--"age": 26,
//--"country": "India"
//}
stringify 如果第三个参数是 string,那么将使用它来代替上面显示的空格字符:
JSON.stringify(user, null,'**');
//{
//**"name": "Prateek Singh",
//**"age": 26,
//**"country": "India"
//}
// 这里 * 取代了空格字符
stringify 有一个叫 toJSON 的方法,它可以作为任意对象的属性。JSON.stringify 返回这个函数的结果并对其进行序列化,而不是将整个对象转换为字符串。参考下面的例子:
const user = {
firstName : "Prateek",
lastName : "Singh",
age : 26,
toJSON() {
return {
fullName: `${this.firstName} + ${this.lastName}`
};
}
}
console.log(JSON.stringify(user));
// 结果
// "{ "fullName" : "Prateek Singh"}"
这里我们可以看到,它只打印 toJSON 函数的结果,而不是打印整个对象。