recursively convert hash containing non-UTF chars to UTF

后端 未结 2 1620
臣服心动
臣服心动 2021-01-19 05:08

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 ele

相关标签:
2条回答
  • 2021-01-19 05:47

    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
    
    0 讨论(0)
  • 2021-01-19 06:00

    try this:

    json_string = not_encoded_hash.to_json.dup.encode("UTF-8")
    encoded_hash = JSON.parse(json_string).with_indifferent_access
    
    0 讨论(0)
提交回复
热议问题