【问题标题】:Rails sanitize method replaces single quotes with double quotesRails sanitize 方法用双引号替换单引号
【发布时间】:2016-01-27 23:55:23
【问题描述】:

rails sanitize 方法在看到锚标记时将单引号替换为双引号。

例子

sanitize("<a href='https://google.com'>google</a>")
=> "<a href=\"https://google.com\">google</a>"

这是有问题的,因为在我的应用程序中,我正在清理可能包含这些字符串的 JSON 有效负载,这会导致 JSON 格式错误。

JSON.parse("{\"link\":\"<a href='https://google.com'>google</a>\"}")
=> {"link"=>"<a href='https://google.com'>google</a>"}

JSON.parse(sanitize(("{\"link\":\"<a href='https://google.com'>google</a>\"}"))
=> JSON::ParseError

我无法控制输入字符串。有什么办法可以防止单引号转双引号?

【问题讨论】:

  • 为什么不只清理用户输入(我不认为键是用户输入)而不是完整的 json?

标签: ruby-on-rails json ruby-on-rails-3 ruby-on-rails-4


【解决方案1】:

这应该可行。无需清理完整的 json,您可以先清理用户输入,然后从中创建一个 json:

link_html = "<a href='https://google.com'>google</a>"
data = {"link" => sanitize(link_html)}.to_json

它将创建一个像这样的json:

"{\"link\":\"<a href=\\\"https://google.com\\\">google</a>\"}"

在接收端 JSON.parse 可以正常工作:

irb(main):009:0> JSON.parse("{\"link\":\"<a href=\\\"https://google.com\\\">google</a>\"}")
=> {"link"=>"<a href=\"https://google.com\">google</a>"}

【讨论】:

  • 不,因为用户可能是邪恶的。例如,他们可以编写一个部分 json 来结束您的数据链接并在它们之后添加新字段。
  • 那么您可能应该先清理用户输入,然后再创建 json。我已经更新了答案。
猜你喜欢
  • 2021-08-12
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2018-09-23
  • 2011-01-26
相关资源
最近更新 更多