diff --git a/index.js b/index.js index 7c727b4..6c1caa8 100644 --- a/index.js +++ b/index.js @@ -99,7 +99,15 @@ exports.parse = function(str, reviver) { */ exports.replace = function(str, data) { return str.replace(/\{\{([^}]+)\}\}/g, function(match, search) { - return data[search] ? data[search] : match; + if (data.hasOwnProperty(search)) { + // If the variable is an object, stringify it before replacement. + // The false positive of "null" is fine in this case. + if (typeof data[search] === 'object') { + return JSON.stringify(data[search]); + } + return data[search]; + } + return match; }); }; diff --git a/test/fixtures/conf11.json b/test/fixtures/conf11.json new file mode 100644 index 0000000..c10b575 --- /dev/null +++ b/test/fixtures/conf11.json @@ -0,0 +1,10 @@ +{ + "subobject": { + "test": 5 + }, + "subarray": [ + { + "foo": 7 + } + ] +} \ No newline at end of file diff --git a/test/fixtures/conf12.json b/test/fixtures/conf12.json new file mode 100644 index 0000000..3cb4697 --- /dev/null +++ b/test/fixtures/conf12.json @@ -0,0 +1,8 @@ +{ + "num": 1, + "str": "moo", + "bool": false, + "arr": [], + "obj": {}, + "null": null +} \ No newline at end of file diff --git a/test/fixtures/templates/conf11tmpl.json b/test/fixtures/templates/conf11tmpl.json new file mode 100644 index 0000000..ff07d5d --- /dev/null +++ b/test/fixtures/templates/conf11tmpl.json @@ -0,0 +1,4 @@ +{ + "subobject": {{subobject}}, + "subarray": {{subarray}} +} \ No newline at end of file diff --git a/test/fixtures/templates/conf12tmpl.json b/test/fixtures/templates/conf12tmpl.json new file mode 100644 index 0000000..c5cfd72 --- /dev/null +++ b/test/fixtures/templates/conf12tmpl.json @@ -0,0 +1,8 @@ +{ + "num": {{num}}, + "str": "{{str}}", + "bool": {{bool}}, + "arr": {{arr}}, + "obj": {{obj}}, + "null": {{null}} +} \ No newline at end of file diff --git a/test/test.js b/test/test.js index a72ba39..708a333 100644 --- a/test/test.js +++ b/test/test.js @@ -17,6 +17,24 @@ var data = { conf7: {"key": "{{root}}/src"}, conf8: {}, conf10: {"test":"valid JSON, except for the the hidden BOM character"}, + conf11: { + "subobject": { + "test": 5 + }, + "subarray": [ + { + "foo": 7 + } + ] + }, + conf12: { + "num": 1, + "str": "moo", + "bool": false, + "arr": [], + "obj": {}, + "null": null + } }; a.doesNotThrow(function() { @@ -41,6 +59,12 @@ a.deepEqual(cjson.load(fixtures + '/conf8.json'), data.conf8, 'string-like comme a.deepEqual(cjson.load(fixtures + '/conf10.json'), data.conf10, 'BOM character'); +var conf11 = cjson.load(fixtures + '/conf11.json'); +a.deepEqual(cjson.load(fixtures + '/templates/conf11tmpl.json', {replace: conf11}), data.conf11, 'object and array as template variables'); + +var conf12 = cjson.load(fixtures + '/conf12.json'); +a.deepEqual(cjson.load(fixtures + '/templates/conf12tmpl.json', {replace: conf12}), data.conf12, 'JSON types as template variables'); + var data1 = { conf1: {key: 'value'}, conf6: data.conf6