diff --git a/lib/dust.js b/lib/dust.js index 28167147..057129c1 100644 --- a/lib/dust.js +++ b/lib/dust.js @@ -245,14 +245,7 @@ j: function(value) { return dust.escapeJs(value); }, u: encodeURI, uc: encodeURIComponent, - js: function(value) { - if (!JSON) { - dust.log('JSON is undefined. JSON stringify has not been used on [' + value + ']', WARN); - return value; - } else { - return JSON.stringify(value); - } - }, + js: function(value) { return dust.escapeJSON(value); }, jp: function(value) { if (!JSON) {dust.log('JSON is undefined. JSON parse has not been used on [' + value + ']', WARN); return value; @@ -891,6 +884,17 @@ return s; }; + dust.escapeJSON = function(o) { + if (!JSON) { + dust.log('JSON is undefined. JSON stringify has not been used on [' + o + ']', WARN); + return o; + } else { + return JSON.stringify(o) + .replace(LS, '\\u2028') + .replace(PS, '\\u2029') + .replace(LT, '\\u003c'); + } + }; if (typeof exports === 'object') { module.exports = dust; diff --git a/test/jasmine-test/spec/coreTests.js b/test/jasmine-test/spec/coreTests.js index 1236d480..88ba9036 100755 --- a/test/jasmine-test/spec/coreTests.js +++ b/test/jasmine-test/spec/coreTests.js @@ -969,12 +969,19 @@ var coreTests = [ message: "should escapeJs a string with double quotes when using the j filter" }, { - name: "JSON.stringify filter", + name: "escapeJSON filter", source: "{obj|js|s}", context: { obj: { id: 1, name: "bob", occupation: "construction" } }, expected: JSON.stringify({ id: 1, name: "bob", occupation: "construction" }), message: "should stringify a JSON literal when using the js filter" }, + { + name: "escapeJSON filter with bad characters", + source: "{obj|js|s}", + context: { obj: { name: "<<\u2028testLS \u2029testPS"} }, + expected: '{"name":"\\u003c\\u003c\\u2028testLS \\u2029testPS"}', + message: "should escape bad characters when using the js filter" + }, { name: "JSON.parse filter", source: "{obj|jp}",