Skip to content

Commit 7e139e8

Browse files
author
James Halliday
committed
fixed merge conflicts
1 parent d03f90c commit 7e139e8

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

index.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ module.exports = function (obj, opts) {
55
if (typeof opts === 'function') opts = { cmp: opts };
66
var space = opts.space || '';
77
if (typeof space === 'number') space = Array(space+1).join(' ');
8+
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
9+
810
var cmp = opts.cmp && (function (f) {
911
return function (node) {
1012
return function (a, b) {
@@ -15,9 +17,11 @@ module.exports = function (obj, opts) {
1517
};
1618
})(opts.cmp);
1719

20+
var seen = [];
1821
return (function stringify (node, level) {
1922
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
2023
var colonSeparator = space ? ': ' : ':';
24+
2125
if (typeof node !== 'object' || node === null) {
2226
return json.stringify(node);
2327
}
@@ -30,6 +34,12 @@ module.exports = function (obj, opts) {
3034
return '[' + out.join(',') + indent + ']';
3135
}
3236
else {
37+
if (seen.indexOf(node) !== -1) {
38+
if (cycles) return stringify('__cycle__');
39+
else throw new TypeError('Converting circular structure to JSON');
40+
} else {
41+
seen.push(node);
42+
}
3343
var keys = objectKeys(node).sort(cmp && cmp(node));
3444
var out = [];
3545
for (var i = 0; i < keys.length; i++) {

test/nested.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,23 @@ test('nested', function (t) {
66
var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 };
77
t.equal(stringify(obj), '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}');
88
});
9+
10+
test('cyclic (default)', function (t) {
11+
t.plan(1);
12+
var one = { a: 1 };
13+
var two = { a: 2, one: one };
14+
one.two = two;
15+
try {
16+
stringify(one);
17+
} catch (ex) {
18+
t.equal(ex.toString(), 'TypeError: Converting circular structure to JSON');
19+
}
20+
});
21+
22+
test('cyclic (specifically allowed)', function (t) {
23+
t.plan(1);
24+
var one = { a: 1 };
25+
var two = { a: 2, one: one };
26+
one.two = two;
27+
t.equal(stringify(one, {cycles:true}), '{"a":1,"two":{"a":2,"one":"__cycle__"}}');
28+
});

0 commit comments

Comments
 (0)