重新认识JSON.stringify

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}'

注意:在使用过程中需要知道以上特性,详细特性请查看官网

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜丶陌颜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值