D-Nice D-Nice - 1 year ago 89
Javascript Question

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

I've tried everything. Every combination of the helpers

including some attempts with
. 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.

Answer Source

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)


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

which are roughly the same.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download