Skip to content

Commit

Permalink
Should call 'toJSON' if it is defined on the object being stringified.
Browse files Browse the repository at this point in the history
  • Loading branch information
RickEyre authored and James Halliday committed Apr 3, 2014
1 parent 82b5eab commit c1de9d1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ module.exports = function (obj, opts) {
throw new TypeError('Converting circular structure to JSON');
}
else seen.push(node);


if (node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
var keys = objectKeys(node).sort(cmp && cmp(node));
var out = [];
for (var i = 0; i < keys.length; i++) {
Expand Down
8 changes: 8 additions & 0 deletions test/to-json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
var test = require('tape');
var stringify = require('../');

test('toJSON function', function (t) {
t.plan(1);
var obj = { one: 1, two: 2, toJSON: function() { return { one: 1 }; } };
t.equal(stringify(obj), '{"one":1}' );
});

0 comments on commit c1de9d1

Please sign in to comment.