递归地将包含非UTF字符的哈希转换为UTF
我有一个流氓gem(omniauth),提供包含ASCII-BIT8字符串的数据哈希,我想将其转换为UTF。
如何将哈希的所有字符串元素强制为UTF,作为某种rails初始化方法? .to_utf8
initilizer
session[:omniauth] = omniauth.to_utf8 class Hash def to_utf8 #not really sure what to do here? end end
在Ruby 1.9中,您通常可以使用encode
方法翻转编码。 这个包装器以递归方式转换哈希值,与symbolize_keys
不同,这简单明了:
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
试试这个:
json_string = not_encoded_hash.to_json.dup.encode("UTF-8") encoded_hash = JSON.parse(json_string).with_indifferent_access