How do I preserve undefined values when doing JSON.stringify(hash)?
Here's an example:
var hash = { "name" : "boda", "email" : undefined, "country" : "africa" }; var string = JSON.stringify(hash); > "{"name":"boda","country":"africa"}" Email disappeared from JSON.stringify.
JSON. stringify will omit all object attributes that are undefined .
The JSON-unsafe values on the other hand return : undefined if they are passed as values to the method. null if they are passed as an array element. nothing if passed as properties on an object.
To be clear, the output looks like JSON but in fact is just javascript. JSON. stringify works well in most cases, but "fails" with functions.
The JSON spec does not allow undefined values, but does allow null values.
You can pass a replacer function to JSON.stringify to automatically convert undefined values to null values, like this:
var string = JSON.stringify( obj, function(k, v) { return v === undefined ? null : v; } ); This works for undefined values inside arrays as well, as JSON.stringify already converts those to null.
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