使用Rails在视图中打印有效的,非转义的JSON [英] Print valid, non-escaped JSON in a view with Rails

查看:105
本文介绍了使用Rails在视图中打印有效的,非转义的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了一切。帮助者的每个组合原始 html_safe to_json 包括一些尝试使用 :: JSON.encode CGI.unescape 。问题在于,无论我做什么,我都无法在视图中打印格式良好的JSON。它始终是HTML转义。

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)如果@campaign%> ;;

在我的情况下,它始终是引号被转义为。我会在引号上做一个gsub,但这对于IMO应该是一个非常简单,记录良好的用例来说是一个可怕的解决方案。

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.

推荐答案

这里的问题是=字符串。由于它被认为是不安全的,它会污染另一个字符串。

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

你可以做任何一个:

raw("=" + @campaign.to_json)

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

大致相同。

这篇关于使用Rails在视图中打印有效的,非转义的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆