diff --git a/lib/Parser.js b/lib/Parser.js index b52905e..61ee5af 100644 --- a/lib/Parser.js +++ b/lib/Parser.js @@ -60,7 +60,7 @@ Parser.prototype.clone = function(){ Parser.prototype.read = function(path){ this.path = path; - if (!~path.indexOf('.json')) path += '.json'; + if (!~path.indexOf(this.format.extname)) path += this.format.extname; return this.parse(fs.readFileSync(path, 'utf8')); }; @@ -74,11 +74,12 @@ Parser.prototype.read = function(path){ Parser.prototype.parse = function(str){ var self = this - , plugins = this.plugins; + , plugins = this.plugins + , format = this.format; - if (typeof str !== 'string') str = JSON.stringify(str); + if (typeof str !== 'string') str = format.stringify(str); - return JSON.parse(str, function(key, val){ + return format.parse(str, function(key, val){ var plugin, ret; if ('' === key) return val; for (var i = 0, len = plugins.length; i < len; ++i) { @@ -89,3 +90,17 @@ Parser.prototype.parse = function(str){ return val; }); }; + +/** + * The parser's serialization format. + * By default, exposes the JSON API, but not the actual object, + * so that individual methods may be overwritten. + * + * @api public + */ + +Parser.prototype.format = { + extname: '.json', + parse: JSON.parse, + stringify: JSON.stringify +}; diff --git a/test/parser.js b/test/parser.js index bfe6d45..f6d9ed6 100644 --- a/test/parser.js +++ b/test/parser.js @@ -85,4 +85,35 @@ describe('Parser', function(){ parser.parse(data).should.eql(data); }) }) + + describe('.format', function() { + it('should expose the JSON api by default', function() { + var parser = new Parser + , format = parser.format; + + format.parse.should.equal(JSON.parse); + format.stringify.should.equal(JSON.stringify); + }) + + it('should not be the JSON global', function() { + var parser = new Parser + , format = parser.format; + + format.should.not.equal(JSON); + }) + + it('should accept a custom format object', function() { + var parser = new Parser; + + parser.format = { + parse: function(str) { + return JSON.parse(str.toUpperCase()); + }, + stringify: JSON.stringify + }; + + parser.parse('{ "foo": "bar" }') + .should.eql({ FOO: 'BAR' }); + }) + }) })