Created
February 14, 2023 20:55
-
-
Save jesusgoku/aff22ec92dcb5f5b006fd034ff743cbc to your computer and use it in GitHub Desktop.
JSON.stringify and JSON.parse with custom replacer and reviver
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const someObj = { | |
map: new Map([['uno', 1], ['dos', 2]]), | |
set: new Set([1,2,3,4,5,5,6,7]), | |
obj: { uno: 1, dos: 2 }, | |
arr: [1,2,3,4,5,5,6,7], | |
date: new Date('1991-12-15T00:00:00-0300'), | |
dateISO: '1991-12-15T00:00:00-0300', | |
map: new Map([['uno', new Map([['dos', 2]])]]), | |
}; | |
function replacer(key, value) { | |
if (value instanceof Map) { | |
return { | |
__type: 'Map', | |
value: [...value.entries()], | |
}; | |
} else if (value instanceof Set) { | |
return { | |
__type: 'Set', | |
value: [...value.values()], | |
}; | |
} else if (this[key] instanceof Date) { | |
return { | |
__type: 'Date', | |
value, | |
}; | |
} else { | |
return value; | |
} | |
} | |
function reviver(_, value) { | |
if (value?.__type === 'Map') { | |
return new Map(value.value); | |
} else if (value?.__type === 'Set') { | |
return new Set(value.value); | |
} else if (value?.__type === 'Date') { | |
return new Date(value.value); | |
} else { | |
return value; | |
} | |
} | |
function pipeReplacers(replacers) { | |
return function replacer(key, value) { | |
return replacers.reduce((acc, replacerFn) => { | |
return replacerFn.call(this, key, acc); | |
}, value); | |
} | |
} | |
function mapReplacer(_, value) { | |
return !(value instanceof Map) | |
? value | |
: { __type: 'Map', value: [...value.entries()] }; | |
} | |
function setReplacer(_, value) { | |
return !(value instanceof Set) | |
? value | |
: { __type: 'Set', value: [...value.values()] }; | |
} | |
function dateReplacer(key, value) { | |
return !(this[key] instanceof Date) | |
? value | |
: { __type: 'Date', value }; | |
} | |
const pipedReplacer = pipeReplacers([ | |
mapReplacer, | |
setReplacer, | |
dateReplacer, | |
]); | |
const someObjJson = JSON.stringify(someObj); | |
const someObjJsonWithReplacer = JSON.stringify(someObj, pipedReplacer); | |
console.log(someObjJson); | |
console.log(someObjJsonWithReplacer); | |
const someObjParsed = JSON.parse(someObjJsonWithReplacer); | |
const someObjParsedWithReviver = JSON.parse(someObjJsonWithReplacer, reviver); | |
console.log(someObjParsed); | |
console.log(someObjParsedWithReviver); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment