https://github.com/ftwinston/enhancejson
Parse/stringify object trees to JSON, with support for Map, Set and Date
https://github.com/ftwinston/enhancejson
deserialization json serialization
Last synced: about 1 year ago
JSON representation
Parse/stringify object trees to JSON, with support for Map, Set and Date
- Host: GitHub
- URL: https://github.com/ftwinston/enhancejson
- Owner: FTWinston
- Created: 2021-05-26T08:40:42.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2024-04-09T21:31:57.000Z (about 2 years ago)
- Last Synced: 2025-03-09T05:21:12.454Z (over 1 year ago)
- Topics: deserialization, json, serialization
- Language: TypeScript
- Homepage:
- Size: 205 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
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.
     [](https://github.com/FTWinston/enhancejson/actions/workflows/test.yml)
## 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`.
```javascript
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.