json数组没有变量和分号
var person = { name : 'zhangsan', age : '29', school : { name : 'xiaoxue', location : 'shenzhen' } }; var personJson = JSON.stringify(person); // "{"name":"zhangsan","age":"29","school":{"name":"xiaoxue","location":"shenzhen"}}" JSON.parse(personJson); //Object {name: "zhangsan", age: "29", school: Object}JSON.stringify-接收两个参数,第一个是过滤器,为数组 or 函数; 第二个是缩进量;
var person = { name : 'zhangsan', age : '29', school : { name : 'xiaoxue', location : 'shenzhen' } }; JSON.stringify(person,['name','age']); //"{"name":"zhangsan","age":"29"}"key--属性名;value--属性值
JSON.stringify( person, function( key, value ){ switch( key ){ case "name" : return value + ' man'; default : return value; } });//"{"name":"zhangsan man","age":"29","school":{"name":"xiaoxue man","location":"shenzhen"}}"通过设置undefined 删除属性
JSON.stringify( person, function( key, value ){ if( key == 'name' ) return undefined; else return value; });//"{"age":"29","school":{"location":"shenzhen"}}"字符串缩进 最多10,若为字符最多十个字符
JSON.stringify( person, null, 4); // "{ // "name": "zhangsan", // "age": "29", // "school": { // "name": "xiaoxue", // "location": "shenzhen" // } // }"
JSON.stringify( person, null, "--"); // "{ // --"name": "zhangsan", // --"age": "29", // --"school": { // ----"name": "xiaoxue", // ----"location": "shenzhen" // --} // }"toJSON方法 可以为任何对象添加toJSON()方法
var day = new Date(); day.toJSON(); //"2013-05-26T12:42:24.619Z"
var person = { name : 'zhangsan', age : '29', school : { name : 'xiaoxue', location : 'shenzhen' }, toJSON : function(){ return this.name; } }; JSON.stringify( person ); //""zhangsan""序列化顺序
还原函数
var personJson = JSON.stringify(person); JSON.parse(personJson, function( key, value ){ if( key == "name" ) return value + ' back'; else return value; }); //Object {name: "zhangsan back", age: "29", school: Object}