0

I have one prototype of this structure:

function MyObj() { }

MyObj.prototype = {
    prop1: {
        prop11: null,
        prop12: null,
        prop13: null,
    },
    prop2: {
        prop21: null,
        prop22: null,
        prop23: null,
    },
    prop3: {
        prop31: [],
        prop32: '',
        prop34: [],
    },
    prop4: {
        prop41: null,
    },
}

When I call JSON.stringify(myObjInstance), I get {}, why?

Andy
  • 61,948
  • 13
  • 68
  • 95
  • 2
    Similar to http://stackoverflow.com/questions/12369543/why-is-json-stringify-not-serializing-prototype-values. You can write your custom [`toJSON`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON_behavior) method to avoid that. – maxdec Jan 14 '14 at 13:13

5 Answers5

3

This happens because prop1 through prop4 are properties of the prototype and not of the instantiated object.

You can compare it to something like:

for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
        // add property to bag
    }
}

Only the properties of the object itself are used.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

Because JSON.stringify only includes an object's own properties (specifically, own enumerable properties), not properties an object inherits from its prototypes or any of its own properties that are non-enumerable.

So for example: Live Copy | Live Source

function Foo() { }

Foo.prototype.inherited = true;

var f = new Foo();
Object.defineProperty(f, "ownNonEnumerable", {
    value: true
});

f.ownEnumerable = true;

console.log(f.inherited);        // true
console.log(f.ownNonEnumerable); // true
console.log(f.ownEnumerable);    // true
console.log(JSON.stringify(f));  // {"ownEnumerable": true}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

JSON.stringify will only include a property if it can be found with hasOwnProperty, and

new MyObj().hasOwnProperty("prop1") === false;

Try this instead:

JSON.stringify(MyObj.prototype);
tckmn
  • 57,719
  • 27
  • 114
  • 156
1

JSON.stringify(obj) will output the properties that the object itself has, not its prototype. Its prototype is a different object.

What you're looking for would be something like this

JSON.stringify(MyObj.prototype)
scrblnrd3
  • 7,228
  • 9
  • 33
  • 64
-1

I had the same issue, when I start working with JSON.stringify. In order to create a string the object you create needs to of typeof == object. Otherwise it won't work.

Try to alert the typeOf of MyObj. If it not Object that won't work.

MyObj = {
prop1: {
    prop11: null,
    prop12: null,
    prop13: null,
},
prop2: {
    prop21: null,
    prop22: null,
    prop23: null,
},
prop3: {
    prop31: [],
    prop32: '',
    prop34: [],
},
prop4: {
    prop41: null,
},

}

David Laberge
  • 15,435
  • 14
  • 53
  • 83