1、概念
json是一种格式化的字符串,规定必须使用双引号""
2、序列化
将对象序列化成json格式的字符串
var xiaohua = { name:"xiaohua", age:23, gender:"female", height:"1.65", skills:["javascript","css","java"] } console.log(JSON.stringify(xiaohua));//返回{"name":"xiaohua","age":23,"gender":"female","height":"1.65","skills":["javascript","css","java"]}
加上参数以后,会按缩进输出
console.log(JSON.stringify(xiaohua,null," ")) /*返回结果 { "name": "xiaohua", "age": 23, "gender": "female", "height": "1.65", "skills": [ "javascript", "css", "java" ] }*/
第二的参数表示要筛选的对象键值,如果只想输出指定的属性,可以传入数组
console.log(JSON.stringify(xiaohua,["name","skills"]," ")) /* 返回结果 { "name": "xiaohua", "skills": [ "javascript", "css", "java" ] } */
3、反序列化
将json格式的字符串变成一个js对象
var s = '{"name":"xiaohua","skills":["javascript","css","java"]}' console.log(JSON.parse(s));//返回Object {name: "xiaohua", skills:["javascript","css","java"]}