有没有办法从 UTF-8 编码的文件中删除 BOM?
我知道我所有的 JSON 文件都是以 UTF-8 编码的,但是编辑 JSON 文件的数据录入人员将其保存为带 BOM 的 UTF-8。
当我运行 Ruby 脚本来解析 JSON 时,它失败并出现错误。
我不想手动打开 58+ JSON 文件并转换为没有 BOM 的 UTF-8。
对于 ruby >= 1.9.2,您可以使用该模式r:bom|utf-8
这应该可行(我还没有与 json 结合测试它):
json = nil #define the variable outside the block to keep the data
File.open('file.txt', "r:bom|utf-8"){|file|
json = JSON.parse(file.read)
}
文件中是否存在 BOM 并不重要。
安德鲁指出,File#rewind
不能与 BOM 一起使用。
如果您需要倒带功能,您必须记住位置并更换rewind
with pos=
:
#Prepare test file
File.open('file.txt', "w:utf-8"){|f|
f << "\xEF\xBB\xBF" #add BOM
f << 'some content'
}
#Read file and skip BOM if available
File.open('file.txt', "r:bom|utf-8"){|f|
pos =f.pos
p content = f.read #read and write file content
f.pos = pos #f.rewind goes to pos 0
p content = f.read #(re)read and write file content
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)