Mike Mike - 3 months ago 7
Javascript Question

How do I output a Ruby hash as Javascript?

I’m using Rails 4.2.7. I would like to take my hash created in Rails and output a Javascript variable that contains the hash (same data associations). So I have this in my view

var my_object_names = <%=h my_object_name_hash.to_json %>;


but what is output is

var my_object_names = {&quot;1403913600000&quot;:&quot;Proudun&quot;,&quot;1437782400000&quot;:&quot;BTN Event&quot;,&quot;1466812800000&quot;:&quot;Proud&quot;};


This results in a Javascript error, “SyntaxError: Unexpected token &”. What is a more elegant way to take a Ruby hash and output Javascript that contains the same data?

Answer

You're asking for that value to be HTML escaped with the h function, so you're getting it that way.

The way to do it without escaping is:

<%= object.to_json.html_safe %>
Comments