From 00ecbd21f477aa1cbc877634e85408637eab8af1 Mon Sep 17 00:00:00 2001 From: Elliott Foster Date: Tue, 10 Nov 2015 09:03:19 -0600 Subject: [PATCH 1/2] Prevent comments in JSON --- lib/config.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/config.js b/lib/config.js index 1b8e4ebd..0a0f43c6 100644 --- a/lib/config.js +++ b/lib/config.js @@ -947,8 +947,7 @@ util.parseString = function (content, format) { } } else if (format === 'json') { - // Allow comments in JSON files - configObject = JSON.parse(util.stripComments(content)); + configObject = JSON.parse(content); } else if (format === 'json5') { From a01df75f9af6590abf632cf293243d232c6ba457 Mon Sep 17 00:00:00 2001 From: Elliott Foster Date: Wed, 18 Nov 2015 22:05:07 -0600 Subject: [PATCH 2/2] Fallback to JSON5 parsing if JSON parsing fails The fallback will only use JSON5 if the failure was the result of a comment string. This will provide support for strict JSON as well as maintain support for comments in JSON. --- lib/config.js | 17 ++++++++++++++++- package.json | 5 +++-- test/config/custom-environment-variables.json | 3 ++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/lib/config.js b/lib/config.js index ba461fd3..304f5a18 100644 --- a/lib/config.js +++ b/lib/config.js @@ -947,7 +947,22 @@ util.parseString = function (content, format) { } } else if (format === 'json') { - configObject = JSON.parse(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') { diff --git a/package.json b/package.json index 9fa18ebe..c14095c2 100644 --- a/package.json +++ b/package.json @@ -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" diff --git a/test/config/custom-environment-variables.json b/test/config/custom-environment-variables.json index 18442beb..f906f0b7 100644 --- a/test/config/custom-environment-variables.json +++ b/test/config/custom-environment-variables.json @@ -1,7 +1,8 @@ { + // With a comment "customEnvironmentVariables": { "mappedBy": { "json": "CUSTOM_JSON_ENVIRONMENT_VAR" } } -} \ No newline at end of file +}