编码:: UndefinedConversionError [英] Encoding::UndefinedConversionError

查看:141
本文介绍了编码:: UndefinedConversionError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次尝试将哈希转换成JSON字符串时,我都会从ASCII-8BIT到UTF-8中得到一个Encoding :: UndefinedConversionError - \xC2。我试过[.encode | .force_encoding]([UTF-8|ASCII-8BIT]),用.force_encoding链接.encode,向后切换参数,但没有什么似乎工作,所以我抓住了这样的错误:

  begin 
menu.to_json
rescue Encoding :: UndefinedConversionError
puts $ !. error_char.dump
p $ !.error_char.encoding
end

其中菜单是续集的dataset.to_hash,内容来自一个MySQL数据库,utf8_general_ci编码并返回这个:


\xC2



< #Encoding:ASCII-8BIT>


无论使用什么.encode / .force_encoding,编码永远不会改变。我甚至试图替换字符串.gsub!(/ \\xC2 /),没有运气。



任何想法?

解决方案

  menu.to_s.encode('UTF-8',{
:invalid => ,
:undef =>:replace,
:replace =>'?'
})

这样做完美,我不得不替换一些额外的字符,但没有更多的错误。


I keep getting an "Encoding::UndefinedConversionError - "\xC2" from ASCII-8BIT to UTF-8" every time I try to convert a hash into a JSON string. I tried with [.encode | .force_encoding](["UTF-8" | "ASCII-8BIT" ]), chaining .encode with .force_encoding, backwards, switching parameters but nothing seemed to work so I caught the error like this:

begin
  menu.to_json
rescue Encoding::UndefinedConversionError
  puts $!.error_char.dump
  p $!.error_char.encoding
end

Where menu is a sequel's dataset.to_hash with content from a MySQL DB, utf8_general_ci encoding and returned this:

"\xC2"

<#Encoding:ASCII-8BIT>

The encoding never changes, no matter what .encode/.force_encoding I use. I've even tried to replace the string .gsub!(/\\xC2/) without luck.

Any ideas?

解决方案

menu.to_s.encode('UTF-8', {
  :invalid => :replace,
  :undef   => :replace,
  :replace => '?'
})

This worked perfectly, I had to replace some extra characters but there are no more errors.

这篇关于编码:: UndefinedConversionError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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