我有一個 json 檔案,其中包含以下資料:
{"help":true}
Windows 2016 中的平臺,當我在記事本 中打開文本檔案時,編碼顯示為 UCS-2 LE BOM,當我使用 ruby?? 顯示編碼時,它是 ibm437,當我嘗試決議 json 時,它會出現以下錯誤:
ruby/2.5.0/json/common.rb:156:in `parse': 765: unexpected token at ' ■{' (JSON::ParserError)
我的代碼如下:
require 'json'
def current_options
dest='C:/test.json'
file = File.read(dest)
if(File.exist?(dest))
p file.encoding
p file
@data_hash ||= JSON.parse(file)
return @data_hash
else
return {}
end
end
p current_options
輸出如下所示:
PS C:\> & "C:\ruby\bin\ruby.exe" .\ruby.rb #this is the file that contains my above code
#<Encoding:IBM437>
"\xFF\xFE{\x00\"\x00h\x00e\x00l\x00p\x00\"\x00:\x00t\x00r\x00u\x00e\x00}\x00"
Traceback (most recent call last):
3: from ./ruby.rb:20:in `<main>'
2: from ./ruby.rb:13:in `current_options'
1: from C:/ruby/lib/ruby/2.5.0/json/common.rb:156:in `parse'
C:/ruby/lib/ruby/2.5.0/json/common.rb:156:in `parse': 765: unexpected token at ' ■{' (JSON::ParserError)
如果我使用 notepad 將編碼從 UCS-2 LE BOM 更改為 utf-8,然后在我的代碼中決議它,它可以正常作業,問題是另一個應用程式管理這個檔案并在該編碼格式下創建它。
PS C:\> & "C:\ruby\bin\ruby.exe" .\ruby.rb #this is the file that contains my above code
#<Encoding:IBM437>
"{\"help\":true}"
{"help"=>true}
我嘗試指定編碼并強制它使用 utf-8 但它仍然失敗:
require 'json'
def current_options
dest='C:/test.json'
file = File.read(dest,:external_encoding => 'ibm437',:internal_encoding => 'utf-8')
if(File.exist?(dest))
p file.encoding
p file
@data_hash ||= JSON.parse(file)
return @data_hash
else
return {}
end
end
p current_options
會輸出這個:
PS C:\> & "C:\ruby\bin\ruby.exe" .\ruby.rb #this is the file that contains my above code
#<Encoding:UTF-8>
"\u00A0\u25A0{\u0000\"\u0000h\u0000e\u0000l\u0000p\u0000\"\u0000:\u0000t\u0000r\u0000u\u0000e\u0000}\u0000"
Traceback (most recent call last):
3: from ./ruby.rb:20:in `<main>'
2: from ./ruby.rb:13:in `current_options'
1: from C:/ruby/lib/ruby/2.5.0/json/common.rb:156:in `parse'
C:/ruby/lib/ruby/2.5.0/json/common.rb:156:in `parse': 765: unexpected token at ' ■{' (JSON::ParserError)
我不確定如何決議這個檔案,有什么建議嗎?謝謝,
uj5u.com熱心網友回復:
您的檔案確實位于帶有 BOM 的 UCS2-LE 中,因此 Notepad 告訴您真相。
據我所知,Ruby 并沒有試圖弄清楚編碼。當你這樣做時:
file = File.read(dest)
if(File.exist?(dest))
p file.encoding
您看到的不是 Ruby 從檔案內容中推斷出的編碼。相反,它是作業系統默認的語言環境編碼。在美國 OEM 安裝的 Windows 上,默認編碼是 IBM 437,這是原始 DOS 編碼。檔案的實際編碼無關緊要。
您應該能夠通過提供將檔案轉換為 UTF-8,external_encoding => 'utf-16'因為 BOM 提供了位元組序資訊。
uj5u.com熱心網友回復:
\u00A0是一個不間斷的空間。\u25A0是一個黑色方塊。\u0000是一個空位元組。這些不是有效的 JSON 字符。您必須剝離或轉換它們。
很可能 Ruby 猜錯了編碼,您的檔案不是真正的 IBM437,而是真正的 UCS2-LE
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446032.html
