This SO post有一个生成 json 的服务器示例 byte order mark . RFC7159 说:
Implementations MUST NOT add a byte order mark to the beginning of a JSON text. In the interests of interoperability, implementations that parse JSON texts MAY ignore the presence of a byte order mark rather than treating it as an error.
当前 yajl因此 jsonlite阻塞在 BOM 上。我想遵循 RFC 建议并忽略 UTF8 字符串中的 BOM(如果存在)。执行此操作的有效方法是什么?一个简单的实现:
if(substr(json, 1, 1) == "\uFEFF"){
json <- substring(json, 2)
}
但是 substr
对于大字符串来说有点慢,我不确定这是执行此操作的正确方法。在 R 或 C 中是否有更有效的方法来删除 BOM(如果存在)?
最佳答案
一个简单的解决方案:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::string stripBom(std::string x) {
if (x.size() < 3)
return x;
if (x[0] == '\xEF' && x[1] == '\xBB' && x[2] == '\xBF')
return x.substr(3);
return x;
}
/*** R
x <- "\uFEFFabcdef"
print(x)
print(stripBom(x))
identical(x, stripBom(x))
utf8ToInt(x)
utf8ToInt(stripBom(x))
*/
给予
> x <- "\uFEFFabcdef"
> print(x)
[1] "abcdef"
> print(stripBom(x))
[1] "abcdef"
> identical(x, stripBom(x))
[1] FALSE
> utf8ToInt(x)
[1] 65279 97 98 99 100 101 102
> utf8ToInt(stripBom(x))
[1] 97 98 99 100 101 102
编辑:了解 R 在内部是如何做的也可能有用——在许多情况下,R 会剥离 BOM(例如,对于它的扫描仪和文件阅读器)。见:
关于c - 删除 R/C 中的字节顺序标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26746498/