JSON序列化(stringify)對象時排除某些屬性的兩種方法

JavaScript的JSON對象自己就帶有序列化和反序列化的函數,爲 parse 和 stringify,咱們通常使用這兩個函數將JSON對象持久化。

如:

前端

var Persion = {
    username: "Kris",
    password: "1234567890"
}

alert(JSON.stringify(Persion))   //{"username":"Kris","password":"1234567890"}


美中不足的是stringify這個函數會把全部屬性都進行轉換,但有時侯咱們但願排除一些屬性,好比上面的 password。

json

用toJSON隱藏對象的某些屬性


stackoverflow 上面的這篇問答提供了一種解決方案。即複寫toJSON方法:


後端

var Message = function() {
    this.myPrivateProperty = "Secret message";
    this.myPublicProperty = "Message for the public";

    this.toJSON = function() {
        return {
            "public": this.myPublicProperty
        };
    };
}

alert(JSON.stringify(new Message()));    // {"public":"Message for the public"}


JSON在調用stringify時會先檢測該對象的toJSON接口是否存在,若是存在則使用對象自己的toString進行序列化。複寫toJSON不光能夠應用在基於function構造的對象上,還能夠應用在基於Object的對象上,如:

函數

var Persion = {
    name     : 'Kris'
  , password : 1234567890
  , toJSON   : function() { return { name: this.name } }
};

alert(JSON.stringify(Persion));    // {"name": "Kris"}

 

在Object上定義隱藏屬性


複寫toJSON須要實現額外一個接口,在ES5有一個defineProperty方法能夠實現經過配置參數來定義一些特殊的屬性,好比能夠將此屬性設置爲不可枚舉:

var Persion = { name: "Kris", password: "1234567890" }

//設置屬性
Object.defineProperty(Persion, "password", { enumerable: false })

alert(Persion.password);           //1234567890
alert(JSON.stringify(Persion));    // {"name": "Kris"}


其實上defineProperty還有一些更高級的屬性,如爲屬性添加get/set方法等,但因不兼容老版IE,所以在前端使用的並很少,多用於後端Node.JS中。this

相關文章
相關標籤/搜索