diff --git a/lib/cycle.js b/lib/cycle.js index 3ab3d9e..66bf2cf 100644 --- a/lib/cycle.js +++ b/lib/cycle.js @@ -104,7 +104,7 @@ exports.decycle = function decycle(object, options, replacer) { // If the value is an object or array, look to see if we have already // encountered it. If so, return a $ref/path object. - if (typeof value === 'object' && value !== null) { + if (typeof value === 'object' && options['refs']) { var foundPath = map.get(value); if (foundPath) { if (hasCircular && path.indexOf(foundPath) === 0) { diff --git a/lib/index.js b/lib/index.js index c32b85b..c39f06b 100644 --- a/lib/index.js +++ b/lib/index.js @@ -27,6 +27,7 @@ exports.stringify = function stringify(value, replacer, space, _options) { 'infinity': options } } + if (typeof options.refs === 'undefined') options.refs = true; var decycled = cycle.decycle(value, options, replacer); if (arguments.length === 1) { diff --git a/test/unit.js b/test/unit.js index 4f2a851..ee0aa23 100644 --- a/test/unit.js +++ b/test/unit.js @@ -190,6 +190,15 @@ describe('jsan', function() { assert.equal(jsan.stringify(obj, null, null, {circular: function() { return '∞!' }}), '{"self":"∞!","a":1,"b":{},"c":{"$jsan":"$.b"}}'); }); + it('can use the refs option', function() { + var obj1 = { a: 1 }; + var obj = { "prop1": obj1, "prop2": { "prop3": obj1 } }; + assert.equal(jsan.stringify(obj, null, null, {refs: true}), '{"prop1":{"a":1},"prop2":{"prop3":{"$jsan":"$.prop1"}}}'); + assert.equal(jsan.stringify(obj, null, null, true), '{"prop1":{"a":1},"prop2":{"prop3":{"$jsan":"$.prop1"}}}'); + assert.equal(jsan.stringify(obj, null, null, false), '{"prop1":{"a":1},"prop2":{"prop3":{"$jsan":"$.prop1"}}}'); + assert.equal(jsan.stringify(obj, null, null, {refs: false}), '{"prop1":{"a":1},"prop2":{"prop3":{"a":1}}}'); + }); + it('works on objects with "[", "\'", and "]" in the keys', function() { var obj = {}; obj['["key"]'] = {};