JSON对象的stringify()和parse()方法
1、stringify() ---- JavaScript对象序列化为JSON字符串
eg1.
var book = {title: 'JS',
authors: ['Van'],
edition:3,
year:2011};
var jsonText = JSON.stringify(book);
默认情况下JSON.strigify(book)输出的JSON字符串不包含任何空格字符或缩进,因此保存在jsonText中的字符串如下:
{"title":"JS","autors":["Van"],"edition":3,"year":2011}
eg2.过滤结果
var jsonText = JSON.stringify(book,["title","edition"]);
返回结果:{"title":"JS","edition":3}
eg3.过滤函数
var jsonText = JSON.stringify(book,function(key,value){
switch(key){
case "authors": return value.join(",");
case "year": return 5000;
case "edition": return undefined;
default: return value;
}
});
返回结果:{"title":"JS","autors":"Van","year":5000}
2、parse() ---- 把JSON字符串解析为原生JavaScript值
eg1.
var bookCopy = JSON.parse(jsonText);
保存在bookCopy中即是book的内容
eg2.解析选项
在将日期字符串转换为Date对象时,经常要用到还原函数
var book = {title: 'JS',
authors: ['Van'],
edition:3,
year:2011,
releaseDate:new Date(2011,11,1)};
var jsonText = JSON.stringify(book);
var bookCopy = JSON.parse(jsonText,function(key,value){
if(key == "releaseDate"){ return new Date(value); }
else{ return value; }
});