Hide certain values in output from JSON.stringify()

后端 未结 13 1513
有刺的猬
有刺的猬 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:30

    I've used toJSON solution based on a small library that i've written in order to get Typing at Runtime https://stackoverflow.com/a/55917109/4236151

    0 讨论(0)
  • 2020-12-02 15:30

    Here's another approach, although without Internet Explorer support.

    const privateProperties = ["privateProperty1", "privateProperty2"];
    const excludePrivateProperties = (key, value) => privateProperties.includes(key) ? undefined : value;
    
    const jsonString = JSON.stringify(x, excludePrivateProperties);
    
    0 讨论(0)
  • 2020-12-02 15:31

    Another good solution: (requires underscore)

    x.toJSON = function () {
        return _.omit(this, [ "privateProperty1", "privateProperty2" ]);
    };
    

    The benefit of this solution is that anyone calling JSON.stringify on x will have correct results - you don't have to alter the JSON.stringify calls individually.

    Non-underscore version:

    x.toJSON = function () {
        var result = {};
        for (var x in this) {
            if (x !== "privateProperty1" && x !== "privateProperty2") {
                result[x] = this[x];
            }
        }
        return result;
    };
    
    0 讨论(0)
  • 2020-12-02 15:31

    Object.create is another solution that is close to the defineProperty solution (properties are defined in the same way) but in this way you define the properties to expose from the beginning. In this way you can expose only the properties that you want by setting the property enumerable value to true (false by default), JSON.stringify is ignoring non-enumerable properties, the downside is that this property will also be hidden when using for-in loop on the object or functions like Object.keys.

    var x = Object.create(null, {
        x: {value:0, enumerable: true}, 
        y:{value: 0, enumerable: true}, 
        divID: {value: 'xyz', enumerable: true}, 
        privateProperty1: {value: 'foo'}, 
        privateProperty2: {value: 'bar'}
    });
    JSON.stringify(x)
    //"{"x":0,"y":0,"divID":"xyz"}"
    
    0 讨论(0)
  • 2020-12-02 15:32

    you can do it easily with ES2017

    let {privateProperty1:exc1, privateProperty2:exc2, ...foo} = {
        x:0,
        y:0,
        divID:"xyz",
        privateProperty1: 'foo',
        privateProperty2: 'bar'
    }
    

    Here privateProperty1 and privateProperty2 are assigned to exc1 and exc2 accordingly. The remainings are assigned to foo newly created variable

    0 讨论(0)
  • 2020-12-02 15:34

    The Mozilla docs say to return undefined (instead of "none"):

    http://jsfiddle.net/userdude/rZ5Px/

    function replacer(key,value)
    {
        if (key=="privateProperty1") return undefined;
        else if (key=="privateProperty2") return undefined;
        else return value;
    }
    
    var x = {
        x:0,
        y:0,
        divID:"xyz",
        privateProperty1: 'foo',
        privateProperty2: 'bar'
    };
    
    alert(JSON.stringify(x, replacer));
    

    Here is a duplication method, in case you decide to go that route (as per your comment).

    http://jsfiddle.net/userdude/644sJ/

    function omitKeys(obj, keys)
    {
        var dup = {};
        for (var key in obj) {
            if (keys.indexOf(key) == -1) {
                dup[key] = obj[key];
            }
        }
        return dup;
    }
    
    var x = {
        x:0,
        y:0,
        divID:"xyz",
        privateProperty1: 'foo',
        privateProperty2: 'bar'
    };
    
    alert(JSON.stringify(omitKeys(x, ['privateProperty1','privateProperty2'])));
    

    EDIT - I changed the function key in the bottom function to keep it from being confusing.

    0 讨论(0)
提交回复
热议问题