json-stable-stringify
Advanced tools
Comparing version 0.1.0 to 0.1.1
15
index.js
@@ -8,2 +8,4 @@ var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); | ||
if (typeof space === 'number') space = Array(space+1).join(' '); | ||
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; | ||
var cmp = opts.cmp && (function (f) { | ||
@@ -19,5 +21,7 @@ return function (node) { | ||
var seen = []; | ||
return (function stringify (node, level) { | ||
var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; | ||
var colonSeparator = space ? ': ' : ':'; | ||
if (typeof node !== 'object' || node === null) { | ||
@@ -35,2 +39,8 @@ return json.stringify(node); | ||
else { | ||
if (seen.indexOf(node) !== -1) { | ||
if (cycles) return stringify('__cycle__'); | ||
throw new TypeError('Converting circular structure to JSON'); | ||
} | ||
else seen.push(node); | ||
var keys = objectKeys(node).sort(cmp && cmp(node)); | ||
@@ -40,3 +50,6 @@ var out = []; | ||
var key = keys[i]; | ||
var keyValue = stringify(key,0) + colonSeparator + stringify(node[key],level+1); | ||
var keyValue = stringify(key,0) | ||
+ colonSeparator | ||
+ stringify(node[key],level+1) | ||
; | ||
out.push(indent + space + keyValue); | ||
@@ -43,0 +56,0 @@ } |
{ | ||
"name": "json-stable-stringify", | ||
"version": "0.1.0", | ||
"version": "0.1.1", | ||
"description": "deterministic JSON.stringify() with custom sorting to get deterministic hashes from stringified results", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -9,1 +9,21 @@ var test = require('tape'); | ||
}); | ||
test('cyclic (default)', function (t) { | ||
t.plan(1); | ||
var one = { a: 1 }; | ||
var two = { a: 2, one: one }; | ||
one.two = two; | ||
try { | ||
stringify(one); | ||
} catch (ex) { | ||
t.equal(ex.toString(), 'TypeError: Converting circular structure to JSON'); | ||
} | ||
}); | ||
test('cyclic (specifically allowed)', function (t) { | ||
t.plan(1); | ||
var one = { a: 1 }; | ||
var two = { a: 2, one: one }; | ||
one.two = two; | ||
t.equal(stringify(one, {cycles:true}), '{"a":1,"two":{"a":2,"one":"__cycle__"}}'); | ||
}); |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
10167
176