JSON.stringify returning empty string / object.

The other day, I came across an issue where the JSON.stringify method failed to convert one of my objects into a JSON string. Instead of converting my JavaScript object into a JSON string, it returned an empty JSON string.

Undefined values.

In my case, the issue occurred because my object had properties with undefined values. Take a look at the following example, which will reproduce the issue:

var myObject = {
    'example': undefined
};
console.log(myObject);
    
var jsonString = JSON.stringify(myObject);
console.log(jsonString);

If you run the code above, you will see that the variable jsonString is an empty JSON string. This is because the example property in my object contains an undefined value and JSON.stringify does not know what to convert it into.

Replacer function.

To get around this particular issue, you will need to create a “replacer” function and pass it into the second parameter of JSON.stringify.

Take a look at the following example:

var myObject = {
    'property': undefined
};
console.log(myObject);

var replacer = function(k, v) { if (v === undefined) { return null; } return v; };
var jsonString = JSON.stringify(myObject, replacer);
console.log(jsonString);

In the JavaScript code above, I created a “replacer” function that replaces undefined values with null values. I then passed that function in as the second parameter to JSON.stringify.

Note that the same approach can be used if you need to replace other variable types.