JSON 值能夠是:web
JSON 文件的文件類型是 ".json"
JSON 文本的 MIME 類型是 "application/json"json
JSON.stringify(value[, replacer[, space]])
replacer:
可選。用於轉換結果的函數或數組。數組
var str = {"name":"haha", "age":20}; JSON.stringify(str); // {"name":"haha","age":20}
做爲函數,它有兩個參數,鍵(key)值(value)都會被序列化。app
過濾函數以對象中的每個屬性和值做爲輸入,返回值有如下幾種狀況:函數
JSON.stringify(str, function(key, val){ console.log("key is ", key); console.log("val is ", typeof(val)); return val; } //====================== key is val is object key is name val is string key is age val is number // {"name":"haha","age":20}
function replacer(key, value) { if (typeof value === "string") { return undefined; } return value; } var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7}; var jsonString = JSON.stringify(foo, replacer); // {"week":45,"month":7}
若是 replacer 是一個數組,則僅轉換該數組中具備鍵值的成員。成員的轉換順序與鍵在數組中的順序同樣。url
JSON.stringify(str, ["name", "haha", "kk"]); // {"name":"haha"}
space:
可選,文本添加縮進、空格和換行符,若是 space 是一個數字,則返回值文本在每一個級別縮進指定數目的空格,若是 space 大於 10,則文本縮進 10 個空格。space 也能夠使用非數字,如:t。spa
JSON.stringify(str, null, 4); // { "name": "haha", "age": 20 }
若是一個被序列化的對象擁有 toJSON 方法,那麼該 toJSON 方法就會覆蓋該對象默認的序列化行爲。code
var data = { name:"niuzai", info:{ age:18, sex:"male" }, toJSON:function(){ return "by toJSON"; } }; JSON.stringify(data); //""by toJSON"";
JSON.parse(text[, reviver])
reviver:
可選,一個函數,它用來轉換已經被從text字符串轉爲對象的對象,規則以下:對象
function reviver(key,value){ if(key=="webName"){ return "antzone"; } return value; } var jsonStr='{"webName":"螞蟻部落","url":"softwhy.com","age":"2"}'; var obj=JSON.parse(jsonStr,reviver); console.log(obj); // { age: "2", url: "softwhy.com", webName: "antzone" }