Skip to content Skip to sidebar Skip to footer

Excluding Object Properties While Json-stringifying Array Object

hey I have a array object something like this [{ public: 'public', private: 'private', [{ properties: {... }, instance: {..... } },

Solution 1:

Assuming that you're writing JavaScript as your question tags suggest (although your example code looks like it's nearly c#!): you need to override the "toJSON" method of the object you're serializing, not "stringify" nor "getState".

Therefore if you have an object "Message" that has public and "private" properties, you need to define a "toJSON" method that only returns the public property, as shown below:

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

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


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

Solution 2:

Maybe a little late but JSON.stringify signature accepts a replacer function/array. The array whitelists and function you can define however you want.

MDN Documentation

Post a Comment for "Excluding Object Properties While Json-stringifying Array Object"