enhancejson
v1.3.0
Published
Serialize/deserialize json with support for Map, Set & Date
Downloads
24
Maintainers
Readme
enhanceJSON
Stringify/parse object trees to/from JSON, with support for Map, Set and Date.
enhanceJSON offers drop-in replacements for JSON.parse and JSON.stringify, with identical signatures to those methods.
Installation
Run npm install --save enhancejson
Usage
enhanceJSON is used in the same way as you'd call JSON.stringify
/ JSON.parse
.
Internally, it uses a custom replacer and reviver to handle Map
, Set
and Date
values. Objects representing these types are identified by means of a __type
field, which is added automatically. You should avoid using this key in your own data. Alternatively, you can specify a different key to use via the typeKey
parameter on each method.
You can specify your own replacer and/or reviver, which will be used before (for replacers) or after (for revivers) the internal ones, when calling stringify
or parse
.
import * as enhanceJSON from 'enhancejson';
const data = {
val1: 'test',
map: new Map([[1, 'one'], [2, 'two']]),
child: {
sets: [
new Set([1, 2, 3]),
new Set(['a', 'b', 'c']),
],
date: new Date('2024-04-06'),
}
}
const strData = enhanceJSON.stringify(data);
const newData = enhanceJSON.parse(strData);
expect(newData).toEqual(data);
expect(typeof strData).toEqual('string');
expect(strData).toEqual(`{"val1":"test","map":{"__type":"M","v":[[1,"one"],[2,"two"]]},"child":{"sets":[{"__type":"S","v":[1,2,3]},{"__type":"S","v":["a","b","c"]}],"date":{"__type":"D","v":"2024-04-06T00:00:00.000Z"}}}`);
JSON format
When the stringify
function finds a Map
, Set
or Date
value, it will output an object with a __type
key of "M"
, "S"
or "D"
, respectively. Another field on this same object will contain an array (for Map
and Set
) or string (for Date
) representation of the original object.
When the parse
function finds an object with this key, it assumes that it represents the corresponding data type, and will revive it as such.