Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding JSON in a Rails 4 JS/ERB template

I'm trying to embed model data in some javascript in my RoR 4 app. The controller is generating JSON for the model data like so...

def my_controller_method
  @person = Person.find(params[:id])
  @person_json = @person.to_json(only: [:name, :id])
end

and I'd like to use that json in my unobtrusive javascript to create javascript objects using JSON.parse()...

var personJSON = <%= j @person_json %>;
var person = JSON.parse(personJSON);

but the javascript that's generated is...

var personJSON = {\&quot;id\&quot;:1,\&quot;name\&quot;:\&quot;fred\&quot;};
var person = JSON.parse(personJSON);

and the javascript is failing silently.

When searching for a solution, I found this question asked on SO, but when I try to use the html_safe method, my rails app crashes saying html_safe is an unknown method.

Thanks in advance for your help!

like image 609
BeachRunnerFred Avatar asked Oct 06 '14 22:10

BeachRunnerFred


3 Answers

What about this:

var personJSON = <%= @person_json.to_json.html_safe %>

or

var personJSON = <%= raw @person_json %>

I think the last option is better for your particular case.

like image 57
rogelio Avatar answered Nov 06 '22 03:11

rogelio


You need to escape the JSON with escape_javascript:

var personJSON = "<%= escape_javascript @person_json %>";

You can also shorten this to:

var personJSON = "<%= j @person_json %>";
like image 1
infused Avatar answered Nov 06 '22 04:11

infused


Works great on my rails 5.0

Controller

# foo.rb
@data = [{key1: 'value1', key2: 'value2'}, {key3: 'value3'}]

View

# foo.js.erb
var arr = JSON.parse("<%= escape_javascript(render(inline: @data.to_json)) %>")
console.log(arr) # (2) [Object, Object]
like image 1
Ray Lee Avatar answered Nov 06 '22 02:11

Ray Lee