window.JSON 对象,处理JSON对象与字符串之间的转化。
浏览器支持:IE8+, Firefox 3.5+, Safari 4+, Chrome, and Opera 10.5+.
跨浏览器的解决方案,可以引用第三方库json2.js :https://github.com/douglascrockford/JSON-js
JSON.stringify(value[, replacer [, space]]) —— 把数据对象转化为字符串。
注意: 1)默认跳过函数; 2)Date 类型将自动转为字符串。
参数介绍:
value: 被序列号的对象;对象可以自定义 toJSON() 方法,更改序列化结果。
replacer: 对象序列化调用的函数;数字或字符串的数组,指定对象中需要被序列号的属性。
当replacer是一个函数时候,它的返回值将影响对象属性的序列化结果:
1) 返回 undefined ,对象的该属性将被删除;
2)返回一个 Object 对象,该 Object 对象将自动被递归序列化;
注意:
改返回对象不能自定义toJSON方法, 否则将导致浏览器崩溃!!!
space: 数字或字符串,为了可读效果,对序列化的字符串插入N个空白或一个特定字符。
注意:
如果自定义了字符,就没办法重新用parse()解析回对象了。
// 例子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;
// DONT'T DO THIS。IE下报堆栈溢出错误,Firefox直接就崩溃了。
// case "transport": return {"transport":value,"toJSON": function(){return "UNKNOW";}};
default: return value;
}
}
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.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 默认仍然是字符串
注意:使用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
参考资料:
https://developer.mozilla.org/en-US/docs/Using_native_JSON
《JavaScript高级程序设计3》
3957

被折叠的 条评论
为什么被折叠?



