Skip to content

Commit

Permalink
Merge pull request #256 from elliotttf/no-json-comments
Browse files Browse the repository at this point in the history
More robust handling of JSON
  • Loading branch information
lorenwest committed Nov 20, 2015
2 parents de802cc + a01df75 commit 4b304e5
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 23 deletions.
35 changes: 16 additions & 19 deletions lib/config.js
Expand Up @@ -947,8 +947,22 @@ util.parseString = function (content, format) {
}
}
else if (format === 'json') {
// Allow comments in JSON files
configObject = JSON.parse(util.stripJSONComments(content));
try {
configObject = JSON.parse(content);
}
catch (e) {
// All JS Style comments will begin with /, so all JSON parse errors that
// encountered a syntax error will complain about this character.
if (e.name !== 'SyntaxError' || e.message !== 'Unexpected token /') {
throw e;
}

if (!JSON5) {
JSON5 = require('json5');
}

configObject = JSON5.parse(content);
}
}
else if (format === 'json5') {

Expand Down Expand Up @@ -1422,23 +1436,6 @@ util.stripYamlComments = function(fileStr) {
return fileStr.replace(/^\s*#.*/mg,'').replace(/^\s*[\n|\r]+/mg,'');
}

/**
* Strip all Javascript type comments from JSON strings.
*
* This method will call util.stripComments but has a simplified regex that
* will work with JSON strings.
*
* @protected
* @method stripJSONComments
* @param fileString {string} The string to strip comments from
* @return {string} The string with comments stripped.
*/
util.stripJSONComments = function(fileStr) {
// Because we are stripping comments from JSON we are only concerned with
// strings that begin and end with a double quote.
return util.stripComments(fileStr, /(""|("(\\"|.)+?"))/g);
};

/**
* Strip all Javascript type comments from the string.
*
Expand Down
5 changes: 3 additions & 2 deletions package.json
Expand Up @@ -18,13 +18,14 @@
"lib": "./lib"
},
"license": "MIT",
"dependencies": {},
"dependencies": {
"json5": "0.4.0"
},
"devDependencies": {
"coffee-script": ">=1.7.0",
"cson": "^3.0.1",
"hjson": "^1.2.0",
"js-yaml": "^3.2.2",
"json5": "~0.2.0",
"properties": "~1.2.1",
"toml": "^2.0.6",
"vows": ">=0.8.1"
Expand Down
3 changes: 2 additions & 1 deletion test/config/custom-environment-variables.json
@@ -1,7 +1,8 @@
{
// With a comment
"customEnvironmentVariables": {
"mappedBy": {
"json": "CUSTOM_JSON_ENVIRONMENT_VAR"
}
}
}
}
1 change: 0 additions & 1 deletion test/config/default.json
Expand Up @@ -9,7 +9,6 @@
"parm1":"value1"
},
"staticArray": [2,1,3],
// Some comment
"Inline": {"a": "", "b": "1"},
"ContainsQuote": "\"this has a quote\"",
"MoreComplexQuote": "<a href=\"http://localhost:3000/offers/reply?id={{system.contact.value}}\">Test String</a>"
Expand Down

0 comments on commit 4b304e5

Please sign in to comment.