Christian Droulers Christian Droulers - 1 year ago 84
Javascript Question

Object.defineProperty on a prototype prevents JSON.stringify from serializing it

I'm using TypeScript to define some classes and when I create a property, it generates the equivalent to

in the following plunkr:

var Class1 = function () {
this._name = "test1";

Object.defineProperty(Class1.prototype, "Name", {
get: function() { return this._name; },
set: function(value) { this._name = value; },
enumerable: true

JSON.stringify(new Class1()); // Will be "{"_name":"test1"}"

When serializing, it doesn't output the property I just defined.

behave as I'd expect by serializing the defined property. (see the plunkr output).

My actual question is: Is this normal?

If so, how do I work around it in the most efficient way?

Answer Source

You can define a toJSON() method on your prototype to customize how instances are serialized.

Class1.prototype.toJSON = function () {
    return {
        Name: this.Name
JSON.stringify(new Class1()); // Will be '{"Name":"test1"}'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download