JSON和JS对象的一些区别

记一下JSON和js对象的区别:

说到JSON首先想到的是JSON.parse()、JSON.stringify()方法,其实JSON(javascrip Object Notation)JavaScript对象表示法,它是js简单数据格式,或者数据结构.

来看一个例子:

let person={
    
    
    name:'zhangsan',
    age:18,
    ismarry:true,
    say:function(){
    
    
        console.log('我是张三');
    },
    gender:undefined,
    birth:NaN,
    tel:null
}
console.log(JSON.stringify(person));//{"name":"zhangsan","age":18,"ismarry":true,"birth":null,"tel":null}
let obj=  JSON.parse(JSON.stringify(person));
console.log(person);// {name: 'zhangsan',age: 18,ismarry: true,say: [Function: say],gender: undefined, birth: NaN,  tel: null}
console.log(obj);// { name: 'zhangsan', age: 18, ismarry: true, birth: null, tel: null  }

重点来了:注意上面的例子,js对象中,是以键值对的形式存放数据,这些值可以是string,number,boolean,undefined,NaN,函数等形式.
区别:

     1.将js对象转为JSON字符串后,JSON对象的键和值都是用双引号""引起来的.而js的键不需要引号.
     2.将JSON字符串转为JSON对象后,JSON对象的值不能是函数、undefined.
     3.js中值为NaN类型在JSON对象中则会自动变成null.

总结:

JSON JS
数据结构 类的实例
键值对必须加双引号 键不加引号
值不能是函数、undefeated 、NaN 值可以是函数、对象、字符串、数字、boolean等

猜你喜欢

转载自blog.csdn.net/qq_38870665/article/details/108673854