javascript高级程序设计

20.2.2序列化选项

book ={
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      edition:3,
      year:2001
}
//第二个参数为过滤器
JSON.stringify(book,['title',edition]);
//结果为:
{"title":"professsional","edition":3}

过滤器为方法

book ={
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      "edition":3,
      "year":2001
}
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;
  }
});

{"title":"professsional","edition":5000,"authors": "Nicholas c. Zakas"}

第三个参数

book ={
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      "edition":3,
      "year":2001
}
JSON.stringify(book,null,4); //4个空格
jsonText中为
{
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      edition:3,
      "year":2001
}

缩进符

JSON.stringify(book,null,"- -");
jsonText中为
{
--"title":"professsional",
--"autors":[
----"Nicholas c. Zakas"
--]
--edition:3,
--year:2001
}

自定义toJSON()方法

book ={
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      edition:3,
      year:2001,
      toJSON:function(){
        return this.title
      }
}
JSON.stringify(book);

{"title":"professsional","edition":5000,"authors": "Nicholas c. Zakas"}

20.2.3 解析选项

book ={
      "title":"professsional",
      "autors":[
        "Nicholas c. Zakas"
      ],
      edition:3,
      year:2001,
      releaseDate:new Date(2011,11,1)
}
var jsonText = JSON.stringify(book);

var bookCopy = JSON.parse(jsonText,function(key,value){
debugger;
    if(key == "releaseDate"){
        return new Date(value);
    }else{
        return value;
    }
})
alert(bookCopy.releaseDate.getFullYear()); //2011

results matching ""

    No results matching ""