Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving undefined that JSON.stringify otherwise removes

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.

like image 693
bodacydo Avatar asked Oct 24 '14 02:10

bodacydo


People also ask

Does JSON Stringify remove undefined?

JSON. stringify will omit all object attributes that are undefined .

Why is my JSON data 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.

Does JSON Stringify preserve functions?

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.


1 Answers

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.

like image 153
Flimm Avatar answered Sep 19 '22 15:09

Flimm