JSON.stringify()的5个秘密特性

JSON.stringify()是JavaScript开发人员最常用来调试的函数。但为什么用它呢,难道console.log()不能用来做同样的事情吗?不妨试试看。

//Initialize a User object 
const user = { 
 “name” : “Prateek Singh”, 
 “age” : 26 
}console.log(user);RESULT 
// [object Object] 

看!console.log()没有输出我们想要的结果。它输出了[object Object],因为从对象到字符串的默认转换是“[objectObject]”。因此,我们使用JSON.stringify()先将对象转换为字符串,然后把结果输入console控制台,如下所示。

const user = { 
“name” : “Prateek Singh”, 
“age” : 26 
}console.log(JSON.stringify(user));RESULT 
// "{ "name" : "Prateek Singh", "age" :26 }" 

通常,开发人员使用这个stringify函数的方式很简单,像上面那样操作就可以。但是接下来所展示的它隐藏的秘密,可以让你的生活变得轻松。

1:第二个参数(数组)

是的,stringify 函数也可以有第二个参数。它是你在控制台中输入对象的键数组。看起来简单吧?接下来仔细看看。我们有一个“产品”对象,并且想知道产品的名称。当我们输入:

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’sFood”}]},”topping”:[{“id”:”5001",”type”:”None”},{“id”:”5002",”type”:”Glazed”},{“id”:”5005",”type”:”Sugar”},{“id”:”5007",”type”:”PowderedSugar”},{“id”:”5006",”type”:”Chocolate withSprinkles”},{“id”:”5003",”type”:”Chocolate”},{“id”:”5004",”type”:”Maple”}]} 

在记录里很难找到名称键,因为在控制台显示了很多无用的信息。当对象变大时,困难也随之增加。

stringify函数的第二个参数派上用场。不妨重写代码,看看结果如何。

console.log(JSON.stringify(product,[‘name’]);//RESULT 
{"name" : "Cake"} 

问题解决了,与输出整个JSON对象不同,我们可以只输出所需的键,通过在第二个参数中将其作为数组来传递。

2:第二个参数(函数)

也可以将第二个参数作为函数来传递。它根据函数中写入的逻辑计算每个键值对。如果返回未定义(undefined)的键值对就不会输出。想要更好地理解,可以参考下面这个例子。

const user = { 
 “name” : “Prateek Singh”, 
 “age” : 26 
} 
 
  
Passing function as 2nd argument 
// Result 
{ "age" : 26 } 

只有age被输出,typeOf字符串的值会因为功能条件返回undefined。

3:第三个参数是数字

第三个参数控制最终字符串里的间距。如果参数是一个数字,则字符串化中的每个级别,都将缩进这个空格字符数。

Note: '--' represnts the spacingfor understanding purposeJSON.stringify(user, null, 2); 
//{ 
//--"name": "Prateek Singh", 
//--"age": 26, 
//--"country": "India" 
//} 

4:第三个参数是字符串

如果第三个参数是字符串,则用它来代替上面显示的空格字符。

JSON.stringify(user, null,'**'); 
//{ 
//**"name": "Prateek Singh", 
//**"age": 26, 
//**"country": "India" 
//} 
Here * replace the space character. 

这里*替代空格字符。

5:toJSON函数

我们有一个名为toJSON的类函数,它的属性是可以作为任何对象的一部分。JSON.stringify返回这个函数的结果并对其进行字符串化,而不是将全部对象转换为字符串。看看下面的例子。

const user = { 
firstName : "Prateek", 
lastName : "Singh", 
age : 26, 
toJSON() { 
   return { 
     fullName: `${this.firstName} +${this.lastName}` 
   };}console.log(JSON.stringify(user));RESULT 
// "{ "fullName" : "Prateek Singh"}" 

可以看到,它不是输出全部对象,而是只有toJSON函数的结果。

希望你能从stringify()身上学到知识。