在Windows上出现以下错误:
编码:: UndefinedConversionError:从ASCII-8BIT到UTF-8的“\ xEF”
text = File.open(file, 'r:binary', &:read); #opens file and reads it with r:binary flag
puts text; #works i get here, outputs the below file contents
data = JSON.parse(text.force_encoding(Encoding::UTF_8)); #fails here with above error
注意: 我也试过R:UTF-8。
{
"Environments": [
{
"Environment": "UT",
"Configuration_Directory": "configs/",
"Files": [
{
"Source": "Web.ENV.config",
"Destination": "Web.config"
}
]
},
{
"Environment": "UAT",
"Configuration_Directory": "configs/",
"Files": [
{
"Source": "Web.ENV.config",
"Destination": "Web.config"
}
]
},
{
"Environment": "Staging",
"Configuration_Directory": "configs/",
"Files": [
{
"Source": "Web.ENV.config",
"Destination": "Web.config"
}
]
},
{
"Environment": "Production",
"Configuration_Directory": "configs/",
"Files": [
{
"Source": "Web.ENV.config",
"Destination": "Web.config"
}
]
}
]
}
答案 0 :(得分:2)
我遇到了这个问题,原始字符串是带有BOM的UTF-8,但是Ruby将其编码为ASCII-8bit。我将字符串转换为字节数组,然后重新转换为字符串,同时将编码强制为UTF-8。
string_value.bytes.pack("c*").force_encoding("UTF-8")