An open API service indexing awesome lists of open source software.

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

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.

![Version badge](https://badgen.net/npm/v/enhancejson) ![Minified badge](https://badgen.net/bundlephobia/min/enhancejson) ![Minzipped badge](https://badgen.net/bundlephobia/minzip/enhancejson) ![Dependencies badge](https://badgen.net/bundlephobia/dependency-count/enhancejson) ![Types badge](https://badgen.net/npm/types/enhancejson) [![NodeJS CI](https://github.com/FTWinston/enhancejson/actions/workflows/test.yml/badge.svg?event=push)](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.