undefined
is not a valid JSON value so I am using a custom replacer function to serialize it. It works fine. However, when deserializing it, it works for both values and arrays (so my reviver function seems to work) but not for objects where the undefined key disappears. What am I doing wrong?
function serialize(data) {
return JSON.stringify(data, function (key, value) {
if (this[key] === undefined) {
return '__undef__'
}
return value
})
}
function deserialize(data) {
return JSON.parse(data, function (key, value) {
if (this[key] === '__undef__') {
return undefined
}
return value
})
}
const undef = undefined
const obj1 = { undef: undefined }
console.log(serialize(undefined));
console.log(deserialize(serialize(undefined)));
console.log(serialize([undefined]));
console.log(deserialize(serialize([undefined])));
console.log(serialize({ undef: undefined }));
console.log(deserialize(serialize({ undef: undefined })));