- stringify()和parse():分别是将JavaScript对象序列化为JSON字符串和把JSON字符串解析为原生的JavaScript值.
1.stringify():
var book = { title: "Professional JavaScript", authors: [ "Nicholas C. Zakas" ], edition: 3, year: 2011 }; var jsonText = JSON.stringify(book); alert(jsonText); //{"title":"Professional JavaScript","authors":["Nicholas C.Zakas"],"edition":3,"year":2011} var bookCopy = JSON.parse(jsonText);
stringify()还接受一个数组作为第二个参数,数组的值对应将要序列化的对象属性
var book = { title: "Professional JavaScript", authors: [ "Nicholas C. Zakas" ], edition: 3, year: 2011 }; var jsonText = JSON.stringify(book, ["title", "edition"]); alert(jsonText); //{"title":"Professional JavaScript","edition":3}
stringify()还接受一个函数作为第二个参数:
var book = { title: "Professional JavaScript", authors: [ "Nicholas C. Zakas" ], edition: 3, year: 2011 }; var jsonText = JSON.stringify(book, function(key, value){ switch(key){ case "authors": return value.join(",") case "year": return 5000; case "edition": return undefined;//如果返回了undefined.那么相应的属性会被忽略 default: return value; } }); alert(jsonText); //{"title":"Professional JavaScript","authors":"Nicholas C. Zakas","year":5000}
2.toJSON():如果JSON.stringify()不能满足对某些对象进行自定义序列化的需求,可以给对象定义toJSON()方法.
var book = { "title": "Professional JavaScript", "authors": [ "Nicholas C. Zakas" ], edition: 3, year: 2011, toJSON: function(){ return this.title; } }; var jsonText = JSON.stringify(book); alert(jsonText);//"Professional JavaScript"
3.parse()也可以接受一个函数作为第二个参数
var book = { "title": "Professional JavaScript", "authors": [ "Nicholas C. Zakas" ], edition: 3, year: 2011, releaseDate: new Date(2011, 11, 1) }; var jsonText = JSON.stringify(book); console.log(jsonText); //{"title":"Professional JavaScript","authors":["NicholasC.Zakas"],"edition":3,"year":2011,"releaseDate":"2011-11-30T16:00:00.000Z"} var bookCopy = JSON.parse(jsonText, function(key, value){ if (key == "releaseDate"){ return undefined; } else { return value; } }); console.log("releaseDate" in bookCopy);//false console.log(bookCopy);///*Array(1)0:"Nicholas C. Zakas"length:1__proto__:Array(0)edition:3title:"Professional JavaScript"year:2011*/