-
-
Save asen-ruuby/488965671aff6b0865b86c8c7b918d9d to your computer and use it in GitHub Desktop.
JSON custom types serialization/parsing
This file contains 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 OBJECT_TYPE = '[object Object]'; | |
const TYPE_PROP = '__type__'; | |
const VALUE_PROP = '__value__'; | |
const jsParseMap = { | |
'[object BigInt]': BigInt, | |
}; | |
const jsSerializeMap = { | |
'[object BigInt]': (v) => `${v}`, | |
}; | |
const isTypedObject = (v) => { | |
const typeTag = {}.toString.call(v); | |
return ( | |
typeTag === OBJECT_TYPE | |
&& TYPE_PROP in v | |
&& VALUE_PROP in v | |
); | |
}; | |
const replacer = (_, v) => { | |
const typeTag = {}.toString.call(v); | |
if (typeTag in jsSerializeMap) { | |
return { | |
[TYPE_PROP]: typeTag, | |
[VALUE_PROP]: jsSerializeMap[typeTag](v), | |
}; | |
} | |
return v; | |
}; | |
const reviver = (_, v) => { | |
if (isTypedObject(v)) { | |
return jsParseMap[v[TYPE_PROP]](v[VALUE_PROP]); | |
} | |
return v; | |
}; | |
// Example | |
const obj = { | |
foo: 20n, | |
}; | |
const jsonStr = JSON.stringify(obj, replacer); // {"foo":{"__type__":"[object BigInt]","__value__":"20"}} | |
typeof JSON.parse(jsonStr, reviver).foo // bigint; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment