json是一种数据结构,并不丛属于Js。json
JSON的语法能够表示下面三种值:数组
//json的字符串必须使用双引号 'hello'
//注意: //1.末尾不要有分号 //2.对象的属性值必定要加双引号 { "name":"Mary", "age":21 }
['Mary','Lily','Jim']
JSON不支持变量,函数和对象实例。数据结构
JSON.stringify()函数
此方法用于将JavaScript对象序列化为JSON字符串,可接受三个参数。第二个参数为数组this
//结果显示返回值与第二个参数数组中的属性对应 var student={ "name":"Mary", "age":22, "course":["English","Math"], "class":1 } var test1=JSON.stringify(student,["age","name"]);
结果显示返回值与第二个参数数组中的属性对应code
第二个参数为数组对象
var student={ "name":"Mary", "age":22, "course":["English","Math"], "class":1 } //返回undefined表示删除该属性 //能够返回自定义后的值 var test2=JSON.stringify(student,function(key,value){ switch(key){ case "name": return undefined; case "age": return value+1; case "class": return 2; default: return value; } });
结果:blog
//缩进4个空格 var test3=JSON.stringify(student,null,4); //将缩进换成制表符 var test3=JSON.stringify(student,null,"--");
var studentTwo={ "name":"Mary", "age":22, "course":["English","Math"], "class":1, toJSON:function(){ return this.name; } } var test3=JSON.stringify(studentTwo);
只显示了name属性ip
toJSON()能够作过滤器的补充,可是须要理解序列化的内部顺序字符串
JSON.parse()方法
将JSON字符串解析为原生的JavaScript值。
//data是一个JSON字符串 var test4=JSON.parse(data);
JSON.stringify还能够接收另外一个参数,该参数为一个函数,与JSON.stringify的过滤相比,这个函数的做用是还原。
var studentThree={ "name":"Mary", "age":22, "course":["English","Math"], "date":new Date(2019,9,10), "class":1 } var test5=JSON.stringify(studentThree); alert(test5);
结果json字符串
var test6=JSON.parse(test5); alert(test6.date);
结果为2019-10-09T16:00:00.000Z
//若是还原函数返回undefined,表示要删除该函数,若是返回其余值,表示将该值插入到结果中 var test7=JSON.parse(test5,function(key,value){ if(key==="date"){ return new Date(value); }else{ return value; } }); alert(test7);
结果为一个对象
alert(test7.date);
结果:Thu Oct 10 2019 00:00:00 GMT+0800 (中国标准时间)