JSON parsing error with erb on Ruby on Rails

I'm trying to be able to have acess to a JSON file in a script tag in a .erb file which is a view for my Rails project.

I have this in my controller:

@myJSON = JSON(IO.binread("./path/to/file.json"));

And I have tried this in the view file:

<%= javascript_tag do %>
    var thing = <%= @myJSON %>;
<% end %>

But it gives me a SyntaxError in the console SyntaxError: expected property name, got '&', which is pretty obvious because the output in the code is something like:

var thing = [{&quot;sigla&quot;=&gt;&quot;AC&quot;, &quot;nome&quot;=&gt;&quot;Acre&quot;, &quot;cidades&quot;=&gt;[&quot;Rio Branco&quot;, ...]}]

What am I getting wrong?

Upvotes: 0

Views: 164

Answers (1)

Jagdeep Singh
Jagdeep Singh

Reputation: 4920

Try this in javascript_tag:

var thing = <%= @myJSON.to_json.html_safe %>;

Upvotes: 1

Related Questions