Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print valid, non-escaped JSON in a view with Rails

I've tried everything. Every combination of the helpers raw, html_safe to_json including some attempts with ::JSON.encode and CGI.unescape. The issue is that regardless of what I do, I can't print well-formed JSON in a view. It's always HTML escaped.

Here's the code in my view:

var campaignData<%= "=" + (raw @campaign.to_json) if @campaign %>;

In my case, it's always the quotes that are escaped as ". I would just do a gsub on the quotes, but that is a terrible solution to what IMO ought to be a very simple, well documented use case.

like image 620
D-Nice Avatar asked Mar 13 '12 20:03

D-Nice


3 Answers

The problem here is with the "=" string. As it's considered unsafe, it taints the other string.

You can probably do either:

raw("=" + @campaign.to_json)

or

"= #{@campaign.to_json}".html_safe

which are roughly the same.

like image 143
Roman Avatar answered Nov 05 '22 20:11

Roman


Since ActiveSupport 2.3.3 you have been able to do .as_json

like image 15
Jesse Whitham Avatar answered Nov 05 '22 19:11

Jesse Whitham


Did you try escape_javascript?

Here is an example from the *.haml file, which I just added to test my answer.

:javascript
  var foo=$.parseJSON("#{j @albums.to_json}")

Where j is an short alias for escape_javascript.

like image 5
cutalion Avatar answered Nov 05 '22 19:11

cutalion