JSON序列化 解析JSON

來源:互聯網
上載者:User

標籤:io   java   ar   strong   2014   cti   on   c   ef   


var book = {
title : "JavaScript",
authors : ["Nickolas . Zakas"],
edition : 3,
year : 2011
},
jsonText;

JSON序列化

//簡單序列化 SON.stringify接受3個參數 第一個需要序列化的對象 第二個參數是一個過濾器 可以是數組也可以是一個函數
jsonText = JSON.stringify( book );

//過濾 結果只包含過濾器中的欄位

jsonText = JSON.stringify( book, ["title", "edition"] );//數組
jsonText = JSON.stringify( book, function ( key, value ) {
switch ( key ) {
case "authors":
return value.join( "." ); //將authors的值 數組串連為一個字串
case "year":
return 5000;
case "edition":
return undefined; //將edition的值設為undefined 在JSON中值為undefined的屬性會被刪除
default :
return value; //提供default 以便其他值能正常出現在結果中
}
} );

//縮排
jsonText = JSON.stringify( book, null, 4 ); //每個層級縮排4個字元 P568 只要設定了縮排 結果就會自動換行 易讀
jsonText = JSON.stringify( book, null, "--" ); //設定縮排字元為"--"


//toJSON方法 添加toJson方法返回自身
book = {
title : "JavaScript",
authors : ["Nickolas . Zakas"],
edition : 3,
year : 2011,
toJSON : function () {
return this.title;
}
};


解析JSON JSON.parse()
book = {
title : "JavaScript",
authors : ["Nickolas . Zakas"],
edition : 3,
year : 2011,
releaseDate:new Date(2014,12,12)
};
jsonText=JSON.stringify(book);
var bookCopy=JSON.parse(jsonText,function(key,value){
if(key=="releaseDate"){
return new Date(value);
}else{
return value;
}
})

JSON序列化 解析JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.