recursively convert hash containing non-UTF chars to UTF

本秂侑毒 提交于 2019-12-01 21:39:24

问题


I have a rogue gem (omniauth) which provides a hash of data containing ASCII-BIT8 strings that I would like to convert into UTF.

How can I force all of the string elements of the hash into UTF, as some kind of rails initializer method? .to_utf8

initilizer

session[:omniauth] = omniauth.to_utf8

class Hash
  def to_utf8
    #not really sure what to do here?
  end
end

回答1:


In Ruby 1.9 you can usually just flip the encoding using the encode method. A wrapper around this that recursively transforms the hash, not unlike symbolize_keys makes this straightforward:

class Hash
  def to_utf8
    Hash[
      self.collect do |k, v|
        if (v.respond_to?(:to_utf8))
          [ k, v.to_utf8 ]
        elsif (v.respond_to?(:encoding))
          [ k, v.dup.encode('UTF-8') ]
        else
          [ k, v ]
        end
      end
    ]
  end
end



回答2:


try this:

json_string = not_encoded_hash.to_json.dup.encode("UTF-8")
encoded_hash = JSON.parse(json_string).with_indifferent_access


来源:https://stackoverflow.com/questions/7392466/recursively-convert-hash-containing-non-utf-chars-to-utf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!