Ran into a quirk with JSON.stringify()
recently. If you have an object with some keys of value undefined
, they will be omitted when converting to JSON:
var obj = { a: 1, b: undefined };
JSON.stringify(obj); // -> "{"a":1}"
I’m sure there’s a good reason for this (it’s in the spec after all), but I had some data that needed those keys to be conserved. Luckily there’s an optional second parameter you can pass to JSON.stringify()
, a replacer
function, which can be used to modify the data before it’s encoded to JSON.
If we create a quick function to replace all undefined
values with null
:
var replacer = function(key, value) {
return value === undefined ? null : value;
}
And call JSON.stringify()
again with our replacer function as second parameter:
JSON.stringify(obj, replacer); // -> "{"a":1,"b":null}"
All our keys are now preserved.