【问题标题】:Rails: Wrong encoding in format.jsonRails:format.json 中的编码错误
【发布时间】:2015-12-17 13:40:00
【问题描述】:

我有一个渲染 html 和 json 的控制器索引方法:

def index
  @articles = Article.all
  respond_to do |format|
    format.html
    format.json { render text: @articles.to_json }
  end
end

在我的 html 中,一切正常,名称显示为 Müller(带有德语变音符号)。但是,当我渲染 json 时,我会得到像 M\u00fcller 这样的奇怪字符。

当我查看Article 模型中title 属性的编码时,它返回UTF-8

puts @articles.first.attributes["title"]
=> "Müller"
puts @articles.first.attributes["title"].encoding
=> #<Encoding:UTF-8>

但是当我将它转换成 json 时,我得到了错误的字符:

puts @articles.first.attributes.to_json
=> "{\"id\":293,\"title\":\"M\\u00fcller\"}"

我不确定为什么这只发生在 json 中。我正在使用 Rails 3.2.9。

【问题讨论】:

  • 你试过these解决方案吗?
  • 是的,我发现了,它解决了我的问题。但我认为会有更好的解决方案,而不是 hacky
  • 只是在这里大声思考:我猜to_json 应该转义字符,以便生成的 json 可以在任何地方很好地传播,而取消转义主要取决于客户端,因此应该在更高的层次上进行。

标签: ruby-on-rails json


【解决方案1】:

您的 render 调用将您的 JSON 文档显式呈现为 text,这可能是您的问题的根源。试试这个:

format.json { render json: @articles.as_json }

这将通过正常的 Rails JSON 编码路径,该路径非常适合正确处理 UTF-8。

附:对于您的代码示例,这些看起来不像 puts 调用的输出,而是 IRB 值表示的输出 - 在这种情况下,UTF-8 字符的转义只是发生了,因此 IRB 可以为您呈现您的字符串的可粘贴回 IRB 版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2012-02-18
    • 1970-01-01
    • 2011-12-03
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多