Search code examples
javascriptjsonnode.jsejsstringify

JSON stringify issue with NodeJS and EJS


I am doing this

var o = <%- JSON.stringify(object) %>;

in a code with following output

var o = {"_id":"57bafa202acb57b8ab000013","status":"incomplete","title":"<script>alert(1);</script>","updated_at":"2016-08-22T18:42:00+05:30","id":"57bafa202acb57b8ab000013"};

and the following error.

Uncaught SyntaxError: Invalid or unexpected token

There is a title attribute with a "<script>alert(1);</script>" in the object. How do I deal with this?


Solution

  • You need to replace the <'s, for instance by using a Unicode escape:

    var o = <%- JSON.stringify(object).replace(/</g, '\\u003c') %>;