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:
1 2 | var obj = { a: 1, b: undefined };
JSON.stringify(obj);
|
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
:
1 2 3 | var replacer = function (key, value) {
return value === undefined ? null : value;
}
|
And call JSON.stringify()
again with our replacer function as second parameter:
1 | JSON.stringify(obj, replacer);
|
All our keys are now preserved.