你不知道的JSON.stringify()妙用

1 語法

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"}"

2 擴展用法

2.1 replacer

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"}"

2.2 space

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"
}"

2.3 深拷貝

var user = {name: 'andy', isDead: false, age: 11, addr: 'shanghai'};

var temp = JSON.stringify(user);
var user2 = JSON.parse(temp);

3 其餘

JSON.parse() 其實也是支持第二個參數的。功能相似於JSON.stringify的第二個參數的功能。io

4 參考

相關文章
相關標籤/搜索