Skip to content

Commit

Permalink
Merge pull request #540 from jimmyhchan/jsonbadchar
Browse files Browse the repository at this point in the history
escape values (\u2028, \u2029 and <) when using json filter
  • Loading branch information
prashn64 committed Feb 10, 2015
2 parents 40f6b9b + f2dc19c commit 56f90ed
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
20 changes: 12 additions & 8 deletions lib/dust.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down
9 changes: 8 additions & 1 deletion test/jasmine-test/spec/coreTests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}",
Expand Down

0 comments on commit 56f90ed

Please sign in to comment.