Rails escape_javascript通过转义单引号来创建无效的JSON [英] Rails escape_javascript creates invalid JSON by escaping single quotes
本文介绍了Rails escape_javascript通过转义单引号来创建无效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ActionView中的escape_javascript方法以斜体撇号 \'
转义撇号'
,解析时会产生错误作为JSON。
The escape_javascript method in ActionView escapes the apostrophe '
as backslash apostrophe \'
, which gives errors when parsing as JSON.
例如,当我打印时,消息我在这里是有效的JSON:
For example, the message "I'm here" is valid JSON when printed as:
{"message": "I'm here"}
但是,<%= escape_javascript(我在这里)%>
输出我在这里
,导致无效的JSON:
But, <%= escape_javascript("I'm here") %>
outputs "I\'m here"
, resulting in invalid JSON:
{"message": "I\'m here"}
是否有修补程序的补丁,或打印到JSON时转义字符串的替代方法?
Is there a patch to fix this, or an alternate way to escape strings when printing to JSON?
推荐答案
只需在字符串中调用.to_json即可正确转义,例如
Just call .to_json on a string and it will be escaped properly e.g.
"foo'bar".to_json
这篇关于Rails escape_javascript通过转义单引号来创建无效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文