https://github.com/sindresorhus/safe-stringify
Serialize objects to JSON with handling for circular references
https://github.com/sindresorhus/safe-stringify
Last synced: 3 months ago
JSON representation
Serialize objects to JSON with handling for circular references
- Host: GitHub
- URL: https://github.com/sindresorhus/safe-stringify
- Owner: sindresorhus
- License: mit
- Created: 2022-04-01T18:16:15.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2024-06-23T13:15:07.000Z (about 1 year ago)
- Last Synced: 2025-03-28T21:29:00.595Z (3 months ago)
- Language: JavaScript
- Size: 19.5 KB
- Stars: 154
- Watchers: 3
- Forks: 5
- Open Issues: 1
-
Metadata Files:
- Readme: readme.md
- License: license
Awesome Lists containing this project
README
# safe-stringify
> Serialize objects to JSON with handling for circular references
`JSON.stringify()` throws an error if the object contains circular references. This package replaces circular references with `"[Circular]"`.
## Install
```sh
npm install safe-stringify
```## Usage
```js
import safeStringify from 'safe-stringify';const foo = {a: true};
foo.b = foo;console.log(safeStringify(foo));
//=> '{"a":true,"b":"[Circular]"}'console.log(JSON.stringify(foo));
//=> TypeError: Converting circular structure to JSON
```## API
### safeStringify(value, options?)
Returns a string.
*Note: There is no `replacer` option as I didn't need that, but “pull request welcome” if you need it.*
#### value
Type: `unknown`
The value to convert to a JSON string.
#### options
Type: `object`
##### indentation
Type: `'string' | 'number'`
The indentation of the JSON.
By default, the JSON is not indented. Set it to `'\t'` for tab indentation or the number of spaces you want.
## FAQ
### Why another safe stringify package?
The existing ones either did too much, did it incorrectly, or used inefficient code (not using `WeakSet`). For example, many packages incorrectly replaced all duplicate objects, not just circular references, and did not handle circular arrays.
## Related
- [decircular](https://github.com/sindresorhus/decircular) - Remove circular references from objects