Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions lib/Parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
};

Expand All @@ -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) {
Expand All @@ -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
};
31 changes: 31 additions & 0 deletions test/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' });
})
})
})