Mathias S Mathias S - 1 year ago 163
JSON Question

Why does JSON.stringify return empty object notation "{}" for an object that seems to have properties?

The following example shows that

returns the string
for SpeechSynthesisVoice objects:

var voiceObject = window.speechSynthesis.getVoices()[0];
JSON.stringify(voiceObject); //returns "{}"?

Complete example: JSFiddle

Why does it return
and not something like
"{voiceURI: "Google Deutsch", name: "Google Deutsch", lang: "de-DE", localService: false, default: false}"

Note that the above example does not work for chrome or iOS; it is targeted for Mozilla Firefox.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download