Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

The following example shows that JSON.stringify() 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.

like image 823
Chilly Code Avatar asked Jul 23 '16 13:07

Chilly Code


People also ask

What does JSON Stringify do to an object?

JSON.stringify() The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Why JSON Stringify does not work on array?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

Does JSON Stringify nested objects?

stringify does not stringify nested arrays. Bookmark this question. Show activity on this post.

Can JSON Stringify throw an error?

Errors and Edge CasesJSON. stringify() throws an error when it detects a cyclical object. In other words, if an object obj has a property whose value is obj , JSON. stringify() will throw an error.


2 Answers

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.

like image 191
T.J. Crowder Avatar answered Sep 23 '22 02:09

T.J. Crowder


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.

like image 44
heyitsmyusername Avatar answered Sep 20 '22 02:09

heyitsmyusername