编码:: UndefinedConversionError:“\ xC2”从ASCII-8BIT到UTF-8

时间:2023-01-05 20:39:36

I received the following error upon saving a new contact. Is there a way to cast "\xC2" so that it can be forced to be saved in the UTF-8 format?

保存新联系人后收到以下错误。有没有办法投射“\ xC2”,以便可以强制以UTF-8格式保存?

c = Contact.new
c.save!

Encoding::UndefinedConversionError: "\xC2" from ASCII-8BIT to UTF-8: INSERT INTO "contacts" ("body", "created_at", "email", "updated_at") VALUES (?, ?, ?, ?)

编码:: UndefinedConversionError:从ASCII-8BIT到UTF-8的“\ xC2”:INSERT INTO“contacts”(“body”,“created_at”,“email”,“updated_at”)VALUES(?,?,?,?)

2 个解决方案

#1


18  

Your string is in some other encoding, most likely iso-8859-1, so you should run this to convert it:

你的字符串是其他编码,很可能是iso-8859-1,所以你应该运行它来转换它:

"\xC2".encode("iso-8859-1").force_encoding("utf-8")
=> "Ã"

See this question for more information related to this issue.

有关此问题的详细信息,请参阅此问题。

#2


2  

For what it's worth, I had this issue pop up when I read in a code file that had the degree symbol (°) in a comment. Upon encoding it for json, ruby became incredibly unhappy.

为了它的价值,我在读取注释中具有度符号(°)的代码文件时弹出了这个问题。在为json编码后,ruby变得非常不开心。

What threw me for a loop was that there wasn't a "Ã" character in the code, so it's just something to keep in mind.

扔给我一个循环的是,代码中没有“Ô字符,所以这只是要记住的事情。

#1


18  

Your string is in some other encoding, most likely iso-8859-1, so you should run this to convert it:

你的字符串是其他编码,很可能是iso-8859-1,所以你应该运行它来转换它:

"\xC2".encode("iso-8859-1").force_encoding("utf-8")
=> "Ã"

See this question for more information related to this issue.

有关此问题的详细信息,请参阅此问题。

#2


2  

For what it's worth, I had this issue pop up when I read in a code file that had the degree symbol (°) in a comment. Upon encoding it for json, ruby became incredibly unhappy.

为了它的价值,我在读取注释中具有度符号(°)的代码文件时弹出了这个问题。在为json编码后,ruby变得非常不开心。

What threw me for a loop was that there wasn't a "Ã" character in the code, so it's just something to keep in mind.

扔给我一个循环的是,代码中没有“Ô字符,所以这只是要记住的事情。