from:http://blog.csdn.net/gjb724332682/article/details/46682743
前言
json2.js是一個json插件,下載地址:https://github.com/douglascrockford/JSON-js
它包含兩個方法,JSON.stringify(value, replacer, space)和JSON.parse(text, reviver)
JSON.stringify(value, replacer, space)
value
要序列化的值,可以是數組或者對象。
replacer
可選參數,可以是一個函數或者一個數組,函數可以根據鍵替換舊的值,而數組可以決定要序列化的鍵。
space
可選參數,排版用的,如果它是數值,表示在每層縮進多少個空格,如果是字符串,例如 '\t' 或者' ',表示在每層使用這個字符來縮進。
例子
- 1、console.log(JSON.stringify([{a: "誒"}, {b: "比"}]));
- 結果:
- [{"a":"誒"},{"b":"比"}]
- 2、console.log(JSON.stringify([{a: "誒"}, {b: "比"}],null,"\t"));
- 結果:
- [
- {
- "a": "誒"
- },
- {
- "b": "比"
- }
- ]
- 3、console.log(JSON.stringify([{a: "誒"}, {b: "比"}],["a"]));
- 結果:
- [{"a":"誒"},{}]
- 4、var jsonText = JSON.stringify({
- a : "誒",
- b : "比"
- },jsonConvert);
- function jsonConvert(key, value) {
- switch (key) {
- case "a":
- return "A";
- case "b":
- return "B";
- default:
- return value;
- }
- }
- console.log(jsonText);
- 結果:
- {"a":"A","b":"B"}
- 5、有時候JSON.stringify()還是不能滿足對某些對象進行自定義序列化的需求,在這些情況下,可以通過對象上調用toJSON()方法,返回其自身的JSON數據格式。
- 例如:console.log(JSON.stringify({a: "誒",b: "比",toJSON:function(){return "自定義"}});結果是返回"自定義".
JSON.parse(text, reviver)
text
要解析的字符串。
reviver
可選參數,是一個函數,用於過濾和轉換結果,它接收每一對鍵值對並執行這個函數,記住,最后一定要加上return value。
例子
- 1、console.log(JSON.parse('{"a":"誒","b":"比"}'));
- 結果:
- Object { a="誒", b="比"}
- 2、console.log(JSON.parse('{"a":"誒","b":"比"}',function(key,value){
- if(key=="a"){
- return "A";
- }else if(key=="b"){
- return "B";
- }
- return value;
- }));
- 結果:
- Object { a="A", b="B"}