safe-stringify
Serialize objects to JSON with handling for circular references
Last updated 2 years ago by sindresorhus .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ npm install safe-stringify 
SYNC missed versions from official npm registry.

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

npm install safe-stringify

Usage

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.

trace

Type: boolean

Include the full object path in circular reference markers, like [Circular *a.b].

import safeStringify from 'safe-stringify';

const bar = {a: {b: {}}};
bar.a.b.c = bar.a;

console.log(safeStringify(bar, {trace: true}));
//=> '{"a":{"b":{"c":"[Circular *a]"}}}'

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 - Remove circular references from objects

Current Tags

  • 1.3.0                                ...           latest (10 months ago)

6 Versions

  • 1.3.0                                ...           10 months ago
  • 1.2.0                                ...           a year ago
  • 1.1.1                                ...           2 years ago
  • 1.1.0                                ...           3 years ago
  • 0.0.1                                ...           10 years ago
  • 0.0.0                                ...           10 years ago
Maintainers (1)
Downloads
Total 7
Today 0
This Week 0
This Month 7
Last Day 0
Last Week 3
Last Month 0
Dependencies (0)
None
Dev Dependencies (3)
Dependents (1)

© 2010 - cnpmjs.org x YWFE | Home | YWFE