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.
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.
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.
stringify does not stringify nested arrays. Bookmark this question. Show activity on this post.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With