In a Rails 3.1 app, how can I safely embed some JSON data into an HTML document?
Suppose I have this in a controller action:
@tags = [
{name:\"ta
Your code using just @tags.to_json
works in rails3, if you enable it with:
ActiveSupport.escape_html_entities_in_json = true
Otherwise, your other option is this:
var tags_list = <%= raw @tags.to_json.gsub("</", "<\\/") %>;
This saves the client having to parse the whole thing through $
I think that if you try this it will work:
var tags_list = "<%== @tags.to_json.gsub('/', '\/') %>";
(Notice the double == and the " ")
btw, this works but is not a good solution in my opinion:
<script type="text/javascript" charset="utf-8">
//<![CDATA[
var tags_list = <%=raw @tags.to_json.gsub('/', '\/') %>;
// ]]>
</script>
The proper way in 2019 is to wrap obj.to_json
with json_escape function. json_escape
is directly intended for escaping specific HTML symbols inside JSON strings. Example below from the documentation:
json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
# => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
json_escape(json)
# => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
JSON.parse(json) == JSON.parse(json_escape(json))
# => true
It seems this page appears on top of Google Search results, that's why I decided to provide a comment with an update :)