JSON 序列化和反序列化

3,161 阅读2分钟

1.jpg

JSON 序列化和反序列化

最近做一个配置化的项目,那么就涉及到很多表单以及表单数据的传递,传递的数据包含各种类型,当然主要还是以string,boolean,number,object(含 array)为主,通常不会有function之类的。传递过程中涉及到JSON的序列化和反序列化,通常我们编码过程中清楚要处理什么数据,但是传递过程太多或者时间长了增加了别的类型,这其中的parse和stringify就会出问题了,记录下。

回顾 js 的数据类型

  • string

  • boolean

  • number

    • Infinity
    • NaN
  • undefined

  • null

    • typeof null==='object'
    • 虽然如此,但是null===nulltrue,暂时理解为所有的null都是同一个null,指向同一片内存区域,同理undefined===undefined
  • object

    • typeof []==='object'

    • typeof ()=>[]==='object'

    包含 Date,RegExp,Function,Array等

  • Symbol

    • 不是构造函数,不通过new调用。
    • Symbol(1) === Symbol(1) => false

JSON.parse

  • JSON.parse(true)得到true,不会发生变化;false同理。即如果parse。

  • JSON.parse(1)得到1,但是如果parse的是Infinity或者NaN,会报错Uncaught SyntaxError: Unexpected token ${I|N} in JSON at position 0

  • JSON.parse(undefined)会报错Uncaught SyntaxError: Unexpected token u in JSON at position 0

  • JSON.parse(null)依然是null

  • 对于object类型:

    • JSON.parse({})会报错Uncaught SyntaxError: Unexpected token o in JSON at position 0
    • JSON.parse([])会报错Unexpected end of JSON input
    • JSON.parse(()=>[])会报错Unexpected token ( in JSON at position 0
    • JSON.parse(function b(){})会报错Unexpected token u in JSON at position 1
    • JSON.parse(new Date)会报错Unexpected token M in JSON at position 1
    • JSON.parse(new RegExp)会报错 Unexpected token / in JSON at position 0
    • 注意 JSON.parse(new Number)是能得到0的,不会报错,另:typeof new Number'object'
  • 对于最常见的string类型

    • JSON.parse('1')得到数字类型的1
    • JSON.parse('true')得到布尔类型的true
    • JSON.parse('undefined')会报错Unexpected token u in JSON at position 1,同理'Infinity''NaN'都一样
    • JSON.parse('[]')得到数组[],但是如果数组不为空,里面的元素有Infinity NaN undefined等,也是处理不了的,只有null可以,事实上对于parse对象时,也是一样的,遇到这几个都处理不了

JSON.stringify

  • JSON.stringify(true)得到字符串'true'
  • JSON.stringify(1)得到字符串'1'
  • JSON.stringify(NaN)得到字符串'null'
  • JSON.stringify(Infinity)得到字符串'null'
  • JSON.stringify(undefined)得到undefined类型,即不会变
  • JSON.stringify(null)得到字符串'null'
  • JSON.stringify("{}")得到字符串'\'{}\''

总结,别乱parse,最好先判断一下是不是json,可以借鉴ts中的类型工具判断的思路,validator包.也不要对已经stringify的数据再次stringfy。

=_=b,好无聊。。。