blog icon indicating copy to clipboard operation
blog copied to clipboard

JSON.stringify 和 JSON.parse

Open aermin opened this issue 5 years ago • 0 comments

JSON.stringify

json对象序列化成json字符串

console.log(JSON.stringify({name:'aermin',age:18})); // "{"name":"aermin","age":18}"

一道笔试题

当要转化的对象有“环”存在时(子节点属性赋值了父节点的引用),为了避免死循环,JSON.stringify 会抛出异常。

const obj = {
  foo: {
    name: 'foo',
    bar: {
      name: 'bar',
      baz: {
        name: 'baz',
        aChild: null // 待会将指向obj.bar
      }
    }
  }
}
obj.foo.bar.baz.aChild = obj.foo // foo->bar->baz->aChild->foo形成环
JSON.stringify(obj) // => TypeError: Converting circular personucture to JSON

JSON.parse

json字符串反序列化(解析)成json对象

console.log(JSON.parse("{"name":"aermin","age":18}")); // {name: "aermin", age: 18}

使用场景:

1.向后台传递参数、接收后台返回值

              如果后台返回的是一个String(Object序列化后返回),那么需要在js中使用eval或者parse等转化为Object再使用;

              如果返回时传递了类型,比如就是Object,那么直接使用就好

 2.在页面间传递数据,特别是数组时

               需要使用序列化,否则IE会报错:不能执行已经释放Script的代码

参考

aermin avatar Sep 09 '18 13:09 aermin