Embedding JSON in a Rails 4 JS/ERB template

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.


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]

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 %>";