Hide certain values in output from JSON.stringify()

后端 未结 13 1595
有刺的猬
有刺的猬 2020-12-02 15:13

Is it possible to exclude certain fields from being included in the json string?

Here is some pseudo code

var x = {
    x:0,
    y:0,
    divID:\"xyz         


        
13条回答
  •  没有蜡笔的小新
    2020-12-02 15:37

    I know this is already an answered question, but I'd like to add something when using instatiated objects.

    If you assign it using a function, it will not be included on the JSON.stringify() result.

    To access the value, call it as a function as well, ending with ()

    var MyClass = function(){
        this.visibleProperty1 = "sample1";
        this.hiddenProperty1 = function(){ return "sample2" };
    }
    
    MyClass.prototype.assignAnother = function(){
        this.visibleProperty2 = "sample3";
        this.visibleProperty3 = "sample4";
        this.hiddenProperty2 = function(){ return "sample5" };
    }
    
    var newObj = new MyClass();
    console.log( JSON.stringify(newObj) );
    // {"visibleProperty1":"sample1"}
    
    newObj.assignAnother();
    console.log( JSON.stringify(newObj) );
    // {"visibleProperty1":"sample1","visibleProperty2":"sample3","visibleProperty3":"sample4"}
    
    console.log( newObj.visibleProperty2 ); // sample3
    console.log( newObj.hiddenProperty1() ); // sample2
    console.log( newObj.hiddenProperty2() ); // sample5
    

    You can also play around with the concept even when not on instatiated objects.

提交回复
热议问题