Search code examples
javascriptjsontypescriptstringify

How to stringify Javascript function object with properties?


In typescript, a class with static members is compiled into a function when each static member becomes a function object property.

For example:

class Config {
    static debug = true;
    static verbose = false;
}

Becomes

var Config = (function () {
    function Config() {
    }
    Config.debug = true;
    Config.verbose = false;
    return Config;
})();

Invoking JSON.stringify on such function object will result with undefined. What is the right way to stringify in that case?


Solution

  • Note that JSON.stringify does not take the functions. You could do it this way:

    If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized.

    An example:

    Function.prototype.toJSON = Function.prototype.toJSON || function(){
        var props = {};
        for(var x in this){
            if(this.hasOwnProperty(x)) props[x] = this[x]
        }
        return props
    }
    
    var Config = (function () {
        function Config() {
        }
        Config.debug = true;
        Config.verbose = false;
        return Config;
    })();
    
    console.log(JSON.stringify(Config))