Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/oresoftware/safe-stringify
Handles circular objects/references for JS to JSON serialization.
https://github.com/oresoftware/safe-stringify
javascript javascript-library json json-api json-server nodejs npm npm-package
Last synced: 12 days ago
JSON representation
Handles circular objects/references for JS to JSON serialization.
- Host: GitHub
- URL: https://github.com/oresoftware/safe-stringify
- Owner: ORESoftware
- License: mit
- Created: 2018-08-15T05:16:21.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-10-01T01:06:51.000Z (about 5 years ago)
- Last Synced: 2023-03-02T00:26:08.637Z (almost 2 years ago)
- Topics: javascript, javascript-library, json, json-api, json-server, nodejs, npm, npm-package
- Language: TypeScript
- Homepage:
- Size: 26.4 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: license.md
Awesome Lists containing this project
README
[![Version](https://img.shields.io/npm/v/@oresoftware/safe-stringify.svg?colorB=green)](https://www.npmjs.com/package/@oresoftware/safe-stringify)
# @oresoftware/safe-stringify
#### Motivation/purpose for this library:
> [See this Github gist](https://gist.github.com/ORESoftware/10bd74e27728a2aa764df4d6c6ecada8)
### Installation:
>
>```bash
> $ npm i -S '@oresoftware/safe-stringify'
>```
>## For most objects (this is more performant)
```js
import * as safe from '@oresoftware/safe-stringify';
const s = safe.stringify({});
```## For use with more complex deeply-nested objects with arrays:
Note: stringifyDeep is *not* production ready, please don't use it yet,
without improving it and making sure it works for you.```js
import * as safe from '@oresoftware/safe-stringify';
const s = safe.stringifyDeep([{}]);
```For example the following works with `stringifyDeep` but not `stringify`:
```js
const x = {dog:'bark'};
x.mmm = {'zebra': 3};
x.mmm = x;const v = [x,x,x];
v.zzz = v;
v.foo = 5;
v.dog = 3;const mmm = safe.stringifyDeep([v,v,v]);
console.log(mmm);```
## > Using Map and Set, etc
This library does not treat Map and Set or other classes as special. To serialize a Map or Set instance,
you might do:```js
class HasMapAndSet {
constructor(){
this.map = new Map([['one',1], ['two',2]]);
this.set = new Set([1,2,3]);
}
toJSON(){ // use this to transform Map and Set to {} or []
return {
map: Array.from(this.map),
set: Array.from(this.set)
}
}
}console.log(
JSON.stringify(
new HasMapAndSet()
)
);```