gpt4 book ai didi

ruby - 有没有办法从 UTF-8 编码的文件中删除 BOM?

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:47 24 4
gpt4 key购买 nike

有没有办法从 UTF-8 编码的文件中删除 BOM?

我知道我所有的 JSON 文件都是用 UTF-8 编码的,但是编辑 JSON 文件的数据录入人员将它保存为 UTF-8 和 BOM。

当我运行我的 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 并不重要。


Andrew 指出,File#rewind 不能与 BOM 一起使用。

如果您需要倒带功能,您必须记住位置并将 rewind 替换为 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
}

关于ruby - 有没有办法从 UTF-8 编码的文件中删除 BOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5011504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com