JSON 编码错误转义(Rails 3、Ruby 1.9.2) [英] JSON encoding wrongly escaped (Rails 3, Ruby 1.9.2)

查看:22
本文介绍了JSON 编码错误转义(Rails 3、Ruby 1.9.2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,以下工作(打印oké")

In my controller, the following works (prints "oké")

puts obj.inspect

但这不会(呈现oku00e9")

But this doesn't (renders "oku00e9")

render :json => obj

显然 to_json 方法转义了 unicode 字符.有没有办法防止这种情况发生?

Apparently the to_json method escapes unicode characters. Is there an option to prevent this?

推荐答案

如果你深入挖掘源代码,你最终会来到 ActiveSupport::JSON::Encodingescape 方法:

If you dig through the source you'll eventually come to ActiveSupport::JSON::Encoding and the escape method:

def escape(string)
  if string.respond_to?(:force_encoding)
    string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
  end
  json = string.
    gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
    gsub(/([xC0-xDF][x80-xBF]|
           [xE0-xEF][x80-xBF]{2}|
           [xF0-xF7][x80-xBF]{3})+/nx) { |s|
    s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\u&')
  }
  json = %("#{json}")
  json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
  json
end

各种 gsub 调用将非 ASCII UTF-8 强制转换为您所看到的 uXXXX 符号.十六进制编码的 UTF-8 应该可以被任何处理 JSON 的东西所接受,但你总是可以对 JSON(或修改后的 JSON 转义器中的猴子补丁)进行后处理以将 uXXXX 符号转换为原始 UTF-8如有必要.

The various gsub calls are forcing non-ASCII UTF-8 to the uXXXX notation that you're seeing. Hex encoded UTF-8 should be acceptable to anything that processes JSON but you could always post-process the JSON (or monkey patch in a modified JSON escaper) to convert the uXXXX notation to raw UTF-8 if necessary.

我同意强制 JSON 为 7bit-clean 有点虚假,但你去了.

I'd agree that forcing JSON to be 7bit-clean is a bit bogus but there you go.

简答:没有.

这篇关于JSON 编码错误转义(Rails 3、Ruby 1.9.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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