JSON.stringify(value[, replacer[, space]])
通常用法:數組
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user); "{"name":"andy","isDead":false,"age":11,"addr":"shanghai"}"
replacer能夠是函數
或者是數組
。函數
功能1: 改變屬性值
將isDead屬性的值翻譯成0或1,0對應false,1對應truespa
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user, function(key, value){ if(key === 'isDead'){ return value === true ? 1 : 0; } return value; }); "{"name":"andy","isDead":0,"age":11,"addr":"shanghai"}"
功能2:刪除某個屬性
將isDead屬性刪除,若是replacer的返回值是undefined
,那麼該屬性會被刪除。翻譯
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user, function(key, value){ if(key === 'isDead'){ return undefined; } return value; }); "{"name":"andy","age":11,"addr":"shanghai"}"
功能3: 經過數組過濾某些屬性
只須要name屬性和addr屬性,其餘不要。code
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user, ['name', 'addr']); "{"name":"andy","addr":"shanghai"}"
space能夠是數字
或者是字符串
, 若是是數字則表示屬性名前加上空格符號的數量,若是是字符串,則直接在屬性名前加上該字符串。ip
功能1: 給輸出屬性前加上n個空格
字符串
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user, null, 4); "{ "name": "andy", "isDead": false, "age": 11, "addr": "shanghai" }"
功能2: tab格式化輸出
get
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; JSON.stringify(user, null, '\t'); "{ "name": "andy", "isDead": false, "age": 11, "addr": "shanghai" }"
功能3: 搞笑
string
JSON.stringify(user, null, 'good'); "{ good"name": "andy", good"isDead": false, good"age": 11, good"addr": "shanghai" }"
var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'}; var temp = JSON.stringify(user); var user2 = JSON.parse(temp);
JSON.parse() 其實也是支持第二個參數的。功能相似於JSON.stringify的第二個參數的功能。io