JSON.stringify 第二个参数
const person = { name: "JSON", age: undefined }
// 问题1: 当值为undefined 时, 存在属性丢失
console.log(JSON.stringify(person)
// '{"name":"JSON"}'
-
数组
// 格式化指定的属性 console.log(JSON.stringify(person , [name]) // '{"name":"JSON"}'
-
函数
// 格式化的每个属性都会经过该函数的处理。转换。 console.log(JSON.stringify(person , (key, value) => { return typeof value === 'undefined' ? "" : value })) // '{"name":"JSON", "age": ""}'
JSON.stringify需要知道的几大特性
特性一
- undefined、任意的函数以及symbol值,出现在非数组对象的属性值中时在序列化过程中会被忽略
- undefined、任意的函数以及symbol值出现在数组中时会被转换成 null。
- undefined、任意的函数以及symbol值被单独转换时,会返回 undefined
// 1. 对象中存在这三种值会被忽略
console.log(JSON.stringify({
name: 'JSON',
sex: 'boy',
// 函数会被忽略
showName () {
console.log('JSON')
},
// undefined会被忽略
age: undefined,
// Symbol会被忽略
symbolName: Symbol('JSON')
}))
// '{"name":"JSON","sex":"boy"}'
// 2. 数组中存在着三种值会被转化为null
console.log(JSON.stringify([
'JSON',
'boy',
// 函数会被转化为null
function showName () {
console.log('JSON')
},
//undefined会被转化为null
undefined,
//Symbol会被转化为null
Symbol('JSON')
]))
// '["JSON","boy",null,null,null]'
// 3.单独转换会返回undefined
console.log(JSON.stringify(
function showName () {
console.log('JSON')
}
)) // undefined
console.log(JSON.stringify(undefined)) // undefined
console.log(JSON.stringify(Symbol('JSON'))) // undefined
特性二
布尔值、数字、字符串的包装对象在序列化过程中会自动转换成对应的原始值。
console.log(JSON.stringify([new Number(1), new String("JSON"), new Boolean(false)]))
// '[1,"JSON",false]'
特性三
所有以symbol为属性键的属性都会被完全忽略掉,即便 replacer 参数中强制指定包含了它们。
console.log(JSON.stringify({
name: Symbol('JSON'),
}))
// '{}'
特性四
NaN 和 Infinity 格式的数值及 null 都会被当做 null。
console.log(JSON.stringify({
age: NaN,
age2: Infinity,
name: null
}))
// '{"age":null,"age2":null,"name":null}'
注意:在使用过程中需要知道以上特性,详细特性请查看官网