Preserving undefined that JSON.stringify otherwise removes

Solution 1:

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.

Solution 2:

You can preserve the key by converting to null since a valid JSON does not allow undefined;

Simple one liner:

JSON.stringify(obj, (k, v) => v === undefined ? null : v)

Solution 3:

This should do the trick

// Since 'JSON.stringify' hides 'undefined', the code bellow is necessary in
// order to display the real param that have invoked the error.
JSON.stringify(hash, (k, v) => (v === undefined) ? '__undefined' : v)
    .replace(/"__undefined"/g, 'undefined')

Solution 4:

Use null instead of undefined.

var hash = {
  "name" : "boda",
  "email" : null,
  "country" : "africa"
};

var string = JSON.stringify(hash);

> "{"name":"boda","email":null,"country":"africa"}"

Solution 5:

function stringifyWithUndefined(obj, space) {
  const str = JSON.stringify(obj, (key, value) => value === undefined ? '__undefined__' : value, space);
  return str.replace(/"__undefined__"/g, 'undefined');
}

Example:

const obj = {
  name: 'boda',
  email: undefined,
  country: 'africa'
};
console.log(stringifyWithUndefined(obj, 2));

Result:

{
  "name": "boda",
  "email": undefined,
  "country": "africa"
}