[博客学习] JSON.stringify 的局限性

277 阅读1分钟

JSON.stringify 的非常规使用

JSON.stringify({
  a: undefined,
  b: null,
  c: new Date(),
  d() { return 1 },
  e: Symbol(2),
  f: NaN,
  g: Number.POSITIVE_INFINITY,
  h: new Set([1, 2, 3, 2, 1]),
  i: new Map([['id', 1], ['no', 2]]),
  j: /^\d{11}$/
})

序列化后的值长这样

'{"b":null,"c":"2021-12-03T02:38:41.637Z","f":null,"g":null,"h":{},"i":{},"j":{}}'

再反序列化回来长这样

{
  bnull
  c"2021-12-03T02:38:41.637Z"
  fnull
  gnull
  h: {}
  i: {}
  j: {}
}

再试试数组

JSON.stringify([
  undefined,
  null,
  new Date(),
  function() { return 1 },
  Symbol(2),
  NaN,
  Number.POSITIVE_INFINITY,
  new Set([1, 2, 3, 2, 1]),
  new Map([['id', 1], ['no', 2]]),
  /^\d{11}$/
])

变这样了 '[null,null,"2021-12-03T03:02:17.902Z",null,null,null,null,{},{},{}]'

[
  null,
  null,
  "2021-12-03T03:02:17.902Z",
  null,
  null,
  null,
  null,
  {},
  {},
  {}
]

总结一下

在对象中

  • undefined function Symbol 直接忽略
  • Date 变字符串
  • NaN INFINITYnull
  • Set Map RegExp{} 在数组中
  • undefined function Symbol NaN INFINITYnull
  • Date 变字符串
  • Set Map RegExp{}

相关博客的学习笔记

关于JSON.stringify的一些事

JSON.stringify() 的语法:JSON.stringify(value[, replacer [, space]])

  • replacer

对于转换结果进行过滤或处理,可以为函数或者数组。如果是函数,可以自定义方法对序列化结果进行处理,如果是数组,则只有数组中包含的属性名才会被序列化。

  • space

第三个参数指定缩进用的空白字符串,用于美化输出,可以是数字或字符串。

一些需要注意的点

  • 如果不希望被忽略,可以用 replacer 处理一下
  • 对象如果是循环引用的,会抛出错误
  • 不可枚举的属性默认会被忽略
  • 如果对象属性有 toJSON 方法,那么该方法就会替代默认的序列化行为