JSON
--- 一種數據格式
--- 支持的數據類型:字符串、數值、Boolean、null,對象,數組。
JSON對象序列化 --- JSON.stringify()
功能 >>> 把數據對象轉化爲字符串
使用 >>> JSON.stringify(value[, replacer [, space]])
value: 被序列化的對象(PS:對象能夠自定義 toJSON() 方法,以更改序列化結果)
replacer: 對象序列化調用的函數、數字或字符串的數組,指定對象中須要被序列化的屬性。
返回 undefined ,對象的該屬性將被刪除;返回一個 Object 對象,該 Object 對象將自動被遞歸序列化。
space: 數字N或字符串,爲了可讀效果,對序列化的字符串插入N個空白或一個特定字符(PS:若是自定義了字符,就沒辦法從新用parse()解析回對象了)
json
// 例子1: var obj = { "a": 100, "b": 'jack', "c": "www\"kk\"www", "say": function(){alert("hello")}, "d": [1,2,3], "e": {"e1":"hwow"}, "f": true, "g": new Date() }; var str = JSON.stringify(obj); // -- output -- {"a":100,"b":"jack","c":"www\"kk\"www","d":[1,2,3],"e":{"e1":"hwow"},"f":true,"g":"2012-08-21T02:33:22.969"} // 例子2: function censor(key, value) { switch(key){ case "foundation": return {"Company":value,"Modifier": "Shawn"}; case "model": return undefined; case "week" : return 30; // 不要像下面這句那樣作!!返回對象不能自定義toJSON方法;IE下報堆棧溢出錯誤,Firefox直接就崩潰了。 // case "transport": return {"transport":value,"toJSON": function(){return "UNKNOW";}}; default: return value; // 必定要提供default項返回傳入的值,以保證其餘值都能正常出如今結果中。 } } var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; var jsonString = JSON.stringify(foo, censor, "~"); console.log(jsonString); // --- output ---- { ~"foundation": { ~~"Company": "Mozilla", ~~"Modifier": "Shawn" ~},~"week": 30, ~"transport": "car", ~"month": 7 }
還原爲JSON對象 --- JSON.parse()
功能 >>> 將字符串化的數據還原爲JSON對象
使用 >>> JSON.parse(value[, replacer])
value:被還原的對象字符串
replacer: 對象還原調用的函數。若是返回 undefined ,對象的該屬性將被刪除。
數組
var book = { "name" : "程序設計", "pubDate": new Date(2010,1,1), "releaseDate" : new Date(2009,10,10), "price" : 199 } var jsonText = JSON.stringify(book); console.log(jsonText); // {"name":"程序設計","pubDate":"2010-01-31T16:00:00.000Z","releaseDate":"2009-11-09T16:00:00.000Z","price":199} var bookCopy = JSON.parse(jsonText,function(key, value){ if(key === "pubDate"){ return new Date(value); }else if(key === "price"){ return undefined; } return value; }); console.log(typeof bookCopy.price); // undefined 已經被刪除了 console.log(typeof bookCopy.pubDate); // object Date類型 console.log(typeof bookCopy.releaseDate); // string 默認仍然是字符串
PS:
1.使用stringify 方法將對象串行化,則應該使用parse 方法還原。
這在本地存儲的讀取時候,容易犯錯,出現bug:瀏覽器
var aStr = "hello"; var result = JSON.stringify(aStr); console.log(result); // "hello" 注意:這裏先後多了2個雙引號 console.log(result === aStr); // false var aStr2 = JSON.parse(result); //使用parse()方法還原 console.log(aStr === aStr2); // true
2.支持原生JSON對象的瀏覽器:IE8+, Firefox 3.5+, Safari 4+, Chrome, and Opera 10.5+.
實現跨瀏覽器須要用到第三方庫。
3.Date 類型在序列化時將自動轉爲字符串。函數