正常使用是JSON化,便于存储,当打印回车符号之类的console.log()是会不显示出来,也没办法对比,JSON.stringify()便可以解决。
console.log('\n'); // 显示为空
console.log(JSON.stringify('\n')); // "\n"
//初始化一个 user 对象
const user = {
"name" : "Prateek Singh",
"age" : 26
}
console.log(user); // [object Object] node环境执行结果
console.log(JSON.stringify(user)); // "{ "name" : "Prateek Singh", "age" : 26 }"
在日志中很难找到 name 键,因为控制台上显示了很多没用的信息。当对象变大时,查找属性的难度增加。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’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(product, ['name']); // {"name" : "Cake"}
我们还可以传入函数作为第二个参数。它根据函数中写入的逻辑来计算每个键值对。如果返回 undefined,则不会打印键值对。
const user = {
"name" : "Prateek Singh",
"age" : 26
};
console.log(JSON.stringify(user, (key, value) => typeof value === 'string' ? undefined : value)); // {"age":26}
只有 age 被打印出来,因为函数判断 typeOf 为 String 的值返回 undefined。
const user = {
"name" : "Prateek Singh",
"age" : 26,
"country": "India"
};
JSON.stringify(user, null, 2);
// 此处的第三个参数数字2代表空格数
//{
// "name": "Prateek Singh",
// "age": 26,
// "country": "India"
//}
JSON.stringify(user, null, '**');
// 此处的第三个参数字符串**代表空格被替换为**
//{
//**"name": "Prateek Singh",
//**"age": 26,
//**"country": "India"
//}
const user = {
firstName : "Prateek",
lastName : "Singh",
age : 26,
toJSON() {
return {
fullName: `${this.firstName} + ${this.lastName}`
};
}
}
console.log(JSON.stringify(user)); // {"fullName":"Prateek + Singh"}