Socket
Socket
Sign inDemoInstall

json-superstring

Package Overview
Dependencies
0
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.0.0 to 2.0.0

LICENSE

5

CHANGELOG.md
# Change Log
## 2.0
### 2.0.0
* Complete rewrite.
## 1.0

@@ -4,0 +9,0 @@

102

lib/index.js
'use strict';
const msg = {
spaceType: 'Type of options.space must be string, number, or undefined',
checkPropsType: 'Type of options.checkProps must be Boolean or undefined'
};
//
// CONSTANTS
//
const getProp = function(obj, key) {
try {
return obj[key];
} catch(err) {
return {
throws: {
name: err.name,
message: err.message,
stackTrace: err.stackTrace,
code: err.code
}
};
}
};
const visit = function(data, seen, checkProps) {
if (data === null || typeof data !== 'object' || Array.isArray(data)) return data;
if (seen.has(data)) return '[Circular]';
const CIRCULAR = '[Circular]';
const ERR_OPEN = '[';
const ERR_SPEC = ': ';
const ERR_CLOSE = ']';
seen.add(data);
if (!checkProps) return data;
const result = {};
const keys = Object.keys(data);
//
// SAFE COPIER
//
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
result[key] = getProp(data, key);
}
return result;
};
function copy(data, stack) {
if (typeof data !== 'object' || data === null) return data;
module.exports = function(data, options) {
let space = undefined;
let checkProps = false;
const isArray = Array.isArray(data);
const result = (isArray) ? [] : {};
if (typeof options === 'object' && options !== null) {
const spaceT = typeof options.space;
const checkPropsT = typeof options.checkProps;
for (const key in data) {
let val;
if (spaceT !== 'undefined') {
if (spaceT !== 'string' && spaceT !== 'number') {
throw new TypeError(msg.spaceType);
try {
val = data[key];
if (val !== null
&& typeof val !== 'undefined'
&& typeof val.toJSON === 'function'
) {
val = val.toJSON();
}
space = options.space;
} catch (err) {
val = ERR_OPEN + err.name + ERR_SPEC + err.message + ERR_CLOSE;
}
if (checkPropsT !== 'undefined') {
if (checkPropsT !== 'boolean') {
throw new TypeError(msg.checkPropsType);
if (typeof val === 'object') {
if (stack.indexOf(val) > -1) {
val = CIRCULAR;
} else {
stack.push(val);
val = copy(val, stack);
stack.pop();
}
checkProps = options.checkProps;
}
if (isArray) result.push(val);
else result[key] = val;
}
const seen = new Set();
return result;
}
return JSON.stringify(data, (key, value) => {
return visit(value, seen, checkProps);
}, space);
};
//
// MODULE INTERFACE
//
function stringify(data, space) {
const result = copy(data, []);
if (!space) return JSON.stringify(result);
return JSON.stringify(result, null, space);
}
module.exports = stringify;
{
"name": "json-superstring",
"description": "Fast, safe JSON stringification.",
"version": "1.0.0",
"dependencies": {
},
"version": "2.0.0",
"devDependencies": {
"chai": "~3.5.0",
"istanbul": "~0.4.2",
"mocha": "~2.4.5"
"eslint": "^4.9.0",
"eslint-config-airbnb": "^16.1.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-jsx-a11y": "^6.0.2",
"eslint-plugin-react": "^7.4.0",
"fast-safe-stringify": "^1.2.1",
"json-stringify-safe": "^5.0.1",
"mocha": "^3.2.0",
"nyc": "^10.2.0",
"radargun": "^1.0.0",
"safe-json-stringify": "^1.0.4"
},

@@ -17,3 +24,5 @@ "keywords": [

"circular",
"references"
"references",
"merge",
"assign"
],

@@ -27,5 +36,6 @@ "main": "./lib",

"scripts": {
"bench": "radargun ./benchmark/**/*.bench.js",
"lint": "eslint ./**/*.js",
"test": "NODE_ENV=test istanbul cover _mocha tests/unit/**/*.js"
"test": "NODE_ENV=test nyc --reporter=lcov --reporter=text mocha --recursive ./test/unit"
}
}
# json-superstring
The native `JSON.stringify()` method is quite fast, but it lacks safety checks for things like circular references and getter properties that throw errors. The `json-superstring` module wraps `JSON.stringify()`, and includes safety checks for these potentials issues.
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.

@@ -27,3 +27,3 @@ ## Usage

console.log(jsonSuperstring(data));
// prints: {"foo":{"a":"1","b":2,"bar":"[Circular]"}}
// {"foo":{"a":"1","b":2,"bar":"[Circular]"}}
```

@@ -33,17 +33,53 @@

* `jsonSuperstring(data [, options])`:
Stringifies a value in the same manner as `JSON.stringify()`, but prevents circular reference errors.
* `jsonSuperstring(data [, space])`: stringifies a value in the same manner as `JSON.stringify()`, but prevents circular reference errors.
Parameters include:
_Parameters_
+ `data`: _(required)_ the data to stringify.
+ `data`: _(required)_ the data to stringify.
+ `options`: _(optional)_ an object to customize various behavioral aspects of `json-superstring`. Keys include:
+ `space`: _(optional)_ a `String` or `Number` object that's used to insert white space into the output JSON string for readability purposes. If this is a `Number`, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a `String`, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is `null`), no white space is used.
- `space`: _(optional)_ a `String` or `Number` to pass as `JSON.stringify()`'s `space` parameter. Defaults to `undefined`.
## Motivation
- `checkProps` _(optional)_ a `Boolean` indicating whether or not `json-superstring` should perform safety checks on getter properties. Only enable if absolutely necessary, as this check requires an additional pass over all keys on an object. Not all use cases require this check, and leaving it turned off can dramatically improve performance. Defaults to `false`.
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:
## Motivation
1. Best in class [performance](#performance).
There are a number of safe JSON stringify modules out there, and this module has drawn inspiration from them (primarily [`safe-json-stringify`](https://www.npmjs.com/package/safe-json-stringify)). However, the bulk of them focus on ensuring compatibility with the broadest set of legacy browsers as possible. This module is focused on usage within Node.js, and, so, can take advantage of a number of various structures in ECMA Script 2015 that significantly boost performance without working about legacy browser support.
2. Safety checks for both circular references and getter properties that errors.
3. No side effects. Objects passed to `json-stringify` are not modified.
4. Provide ability to specify space param, consistent with `JSON.stringify()`'s functionality.
5. 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 │
└─────────────────────┴────────────┴────────────┴────────────┘
```

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc