Skip to content

Commit c1de9d1

Browse files
RickEyreJames Halliday
authored andcommitted
Should call 'toJSON' if it is defined on the object being stringified.
1 parent 82b5eab commit c1de9d1

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

index.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,10 @@ module.exports = function (obj, opts) {
3939
throw new TypeError('Converting circular structure to JSON');
4040
}
4141
else seen.push(node);
42-
42+
43+
if (node.toJSON && typeof node.toJSON === 'function') {
44+
node = node.toJSON();
45+
}
4346
var keys = objectKeys(node).sort(cmp && cmp(node));
4447
var out = [];
4548
for (var i = 0; i < keys.length; i++) {

test/to-json.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
var test = require('tape');
2+
var stringify = require('../');
3+
4+
test('toJSON function', function (t) {
5+
t.plan(1);
6+
var obj = { one: 1, two: 2, toJSON: function() { return { one: 1 }; } };
7+
t.equal(stringify(obj), '{"one":1}' );
8+
});

0 commit comments

Comments
 (0)