json-superstring
The native JSON.stringify()
method is quite fast, but it lacks safety checks for things like circular references and enumerable getter properties that throw errors. The json-superstring
module wraps JSON.stringify()
, and includes safety checks for these potential issues.
Usage
Add json-superstring
as a dependency in package.json
:
$ npm install json-superstring -S
Then simply call json-superstring
...
const jsonSuperstring = require('json-superstring');
const data = {
foo: {
a: '1',
b: 2
}
};
data.foo.bar = data.foo;
console.log(jsonSuperstring(data));
API
Motivation
There are a number of other safe JSON stringifiers out there, and they all provide some variation of performance and features. The goals of this project are:
-
Best in class performance.
-
Safety checks for both circular references and getter properties that errors.
-
No side effects. Objects passed to json-stringify
are not modified.
-
Provide ability to specify space param, consistent with JSON.stringify()
's functionality.
-
Provide ability to merge multiple objects together and stringify.
Comparison
Name | Performance | White Space | Circular Check | Error Check | No Side Effects |
---|
json-superstring | #1 | ✔ | ✔ | ✔ | ✔ |
fast-safe-stringify | #4 | ✕ | ✔ | ✕ | ✕ |
json-stringify-safe | #3 | ✔ | ✔[*] | ✕ | ✔ |
safe-json-stringify | #2 | ✕ | ✔[*][**] | ✔ | ✕ |
[*] Does not check for circular references when calling an object's toJSON()
method.
[**] While safe-json-stringify
performs circular reference checks, it marks all duplicate object references in a JSON object as [Circular]
regardless if whether or not they are actual circular references.
Performance
The json-stringify
module is very fast compared to other safe JSON stringifiers.
┌─────────────────────┬────────────┬────────────┬────────────┐
│ NAME │ AVG │ MIN │ MAX │
╞═════════════════════╪════════════╪════════════╪════════════╡
│ json-superstring │ 6766 ns │ 5096 ns │ 630665 ns │
├─────────────────────┼────────────┼────────────┼────────────┤
│ fast-safe-stringify │ 9094 ns │ 6922 ns │ 1511836 ns │
├─────────────────────┼────────────┼────────────┼────────────┤
│ json-stringify-safe │ 8738 ns │ 6295 ns │ 1755434 ns │
├─────────────────────┼────────────┼────────────┼────────────┤
│ safe-json-stringify │ 6807 ns │ 4546 ns │ 4177514 ns │
└─────────────────────┴────────────┴────────────┴────────────┘