Skip to content Skip to sidebar Skip to footer

Why Does JSON.stringify Return Empty Object Notation "{}" For An Object That Seems To Have Properties?

The following example shows that JSON.stringify() returns the string '{}' for SpeechSynthesisVoice objects: var voiceObject = window.speechSynthesis.getVoices()[0]; JSON.stringify

Solution 1:

JSON.stringify includes an object's own, enumerable properties (spec) that have values that aren't functions or undefined (as JSON doesn't have those), leaving out ones it inherits from its prototype, any that are defined as non-enumerable, and any whose value is a function reference or undefined.

So clearly, the object you get back from getVoices()[0] has no own, enumerable properties that can be represented in JSON. All of their properties must be either inherited, defined as non-enumerable, or (though it's probably not the case here) functions or undefined.


Solution 2:

You can fix this by doing:

var voiceObject = window.speechSynthesis.getVoices()[0];
var newvoiceObject = $.extend(newvoiceObject,voiceObject);
JSON.stringify(newvoiceObject); //returns correct JSON string

...but keep in mind the object type will change, if you require that the object is of a specific type.


Solution 3:

The answer of T.J Crowder works for me, i was creating my object like this:

Object.defineProperties(completeObj, {
    [attributeName]: {
        value: finalValue
    }
});

I changed for this and the problem was solved:

Object.defineProperties(completeObj, {
    [attributeName]: {
        value: finalValue,
        enumerable: true
    }
});

Post a Comment for "Why Does JSON.stringify Return Empty Object Notation "{}" For An Object That Seems To Have Properties?"