JavaScript基础知识总结——json

2017-08-09  本文已影响0人  More_5897

JSON

基本语法

{
    “address” : {
        “line1” : “555 Main Street”,
        “city” : “Denver”,
        “stateOrProvince” : “CO”,
        “zipOrPostalCode” : “80202”,
        “country” : “USA”
    }
}
{
    “people” : [
        { “firstName”: “John”, “lastName”: “Smith”, “age”: 35 },
        { “firstName”: “Jane”, “lastName”: “Smith”, “age”: 32 }
    ]
}

解析和序列化

var book = {
  "title":"xxxx",
  "authors":["aaa"],
  edition: 3,
  year:2001
};
var jsonText1 = JSON.stringify(book);   //序列化整个对象
var jsonText2 = JSON.stringify(book,["title","edition"]);   //序列对象中与数组中对应的对象。
var jsonText3 = JSON.stringify(book,function(key,value){  //根据switch语句输出对象的序列化对象
  switch(key){
    case:"authors";
     return value.jion(",")
    case:"year"
     return 5000
  }
}
var jsonText4 = JSON.stringify(book,null,1);
//jsonText1
{"title":"xxxx","authors":["aaa"],"edition": 3,"year":2001}
//jsonText4
{
  "title":"xxxx",
  "authors":["aaa"],
  "edition": 3,
  "year":2001
}
var book = {
  "title":"xxxx",
  "authors":["aaa"],
  edition: 3,
  year:2001,
  releaseDate: new Date(2011,11,1)
};
var jsonText1 = JSON.stringify(book);   //序列化整个对象

var book1 = JSON.parse(jsonText1,function(key,value){
  if(key=="releaseDate"){
    return new Date(value);  //将原本的字符串还原成Date对象
  }else{
    return value
  }
}
上一篇下一篇

猜你喜欢

热点阅读