Skip to content

Commit de0debf

Browse files
kapetanJames Halliday
authored andcommitted
Enable toJSON function to return different types
1 parent a723f70 commit de0debf

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

index.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ module.exports = function (obj, opts) {
66
var space = opts.space || '';
77
if (typeof space === 'number') space = Array(space+1).join(' ');
88
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
9-
9+
1010
var cmp = opts.cmp && (function (f) {
1111
return function (node) {
1212
return function (a, b) {
@@ -16,12 +16,15 @@ module.exports = function (obj, opts) {
1616
};
1717
};
1818
})(opts.cmp);
19-
19+
2020
var seen = [];
2121
return (function stringify (node, level) {
2222
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
2323
var colonSeparator = space ? ': ' : ':';
24-
24+
25+
if (node && node.toJSON && typeof node.toJSON === 'function') {
26+
node = node.toJSON();
27+
}
2528
if (typeof node !== 'object' || node === null) {
2629
return json.stringify(node);
2730
}
@@ -39,10 +42,7 @@ module.exports = function (obj, opts) {
3942
throw new TypeError('Converting circular structure to JSON');
4043
}
4144
else seen.push(node);
42-
43-
if (node && node.toJSON && typeof node.toJSON === 'function') {
44-
node = node.toJSON();
45-
}
45+
4646
var keys = objectKeys(node).sort(cmp && cmp(node));
4747
var out = [];
4848
for (var i = 0; i < keys.length; i++) {

test/to-json.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,15 @@ test('toJSON function', function (t) {
66
var obj = { one: 1, two: 2, toJSON: function() { return { one: 1 }; } };
77
t.equal(stringify(obj), '{"one":1}' );
88
});
9+
10+
test('toJSON returns string', function (t) {
11+
t.plan(1);
12+
var obj = { one: 1, two: 2, toJSON: function() { return 'one'; } };
13+
t.equal(stringify(obj), '"one"');
14+
});
15+
16+
test('toJSON returns array', function (t) {
17+
t.plan(1);
18+
var obj = { one: 1, two: 2, toJSON: function() { return ['one']; } };
19+
t.equal(stringify(obj), '["one"]');
20+
});

0 commit comments

Comments
 (0)