JSON Cyclic
A small JavaScript library to replace circular references in object literals with JSONPath references, so that the data can be stringified as JSON.
It also supports re-inserting the circular data after the JSON has been parsed.
This will fix the below TypeErrors:
Chrome: "TypeError: Converting circular structure to JSON"
Firefox: "TypeError: cyclic object value"
Edge: "TypeError: Circular reference in value argument not supported"
Safari: "TypeError: JSON.stringify cannot serialize cyclic structures."
Features
- Accepts Arrays, Objects, or both in combination
- Works with >IE8
- Tiny (~1kB minified)
- No dependencies
Installation
npm install json-cyclic
Usage
// ES2015 // CommonJSconst JSONCyclic =
API
There are only two methods exposed, and neither require any configuration:
decycle
Removes any circular data structures.
See the below usage examples:
// Arraysconst arr= 1 "a" arr2 = arr; JSON; // "{"foo":{"bar":{"$ref":"$.foo"}}}" // Objectsconst obj = foo: bar: null ; objfoobar = objfoo; JSON; // "{"foo":{"bar":{"$ref":"$.foo"}}}"
encycle
Re-inserts any circular data.
See the below:
const arr = 1 "a" $ref: "$" console // true JSON; // TypeError: Converting circular structure to JSON
Tests
npm test