This custom json replacer/reviver allow you to store more types as json and still keep it as valid json.
- Allow you to stringify/parse
- BigInt
- Infinity
- NaN
- Date
- typed arrays & ArrayBuffers as web-safe base64
- Maps & Sets
- Error & TypeError
var obj = {
bigint: 2n,
date: new Date(),
pInf: Infinity,
arr: [2,3],
nInf: -Infinity,
map: new Map([['a', 'b']]),
set: new Set(['a', new Date(), 'a']),
reg: /^f/g,
err: new Error('fail'),
typo: new TypeError('typo'),
empty: null,
binary: new Uint16Array([97]),
buff: new ArrayBuffer(20),
obj: {bday: new Date('1996-08-29')},
str: 'str',
bool: true,
num: 3,
nan: NaN,
invDate: new Date('!'),
// Experimental... creating blob/files are sync but reading it is async.
file: {$f: [[new Uint8Array([97])], 'sample.txt', {type: 'text/javascript'}]},
blob: {$d: [['abc'], {type: 'text/javascript'}]}
}
var str = JSON.stringify(obj, replacer, 2)
var res = JSON.parse(str, reviver)
console.log(str)
console.log(obj)
console.log(res) // pretty much the same as obj
This is simular to bson (ejson) but with a much smaller footprint and different data types
I had some issues trying to find something like this and since I had experience with using the bufferReviver from MDN examples, I kept looking in the wrong direction (need: reviver). Since buffers and arraybuffers encode differently by default, using both a replacer and reviver seemed much more sensible and this gist helped me see the issue more clearly.
The only part of this gist I felt was off, was that it tries to JSON encode but uses data structure that are minimal and unintuitive - making the data significantly harder to work with for a human should they inspect it in encoded form.
As a result, I decided to build something similar, inspired by this, but with a smaller scope: https://gitlab.com/monsterbitar/json-arraybuffer-reviver
Thank you for the inspiration <3