c - 删除 R/C 中的字节顺序标记

标签 c json r utf-8

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(例如,对于它的扫描仪和文件阅读器)。见:

https://github.com/wch/r-source/blob/bfe73ecd848198cb9b68427cec7e70c40f96bd72/src/main/scan.c#L455-L458

https://github.com/wch/r-source/blob/bfe73ecd848198cb9b68427cec7e70c40f96bd72/src/main/connections.c#L3950-L3957

关于c - 删除 R/C 中的字节顺序标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26746498/

相关文章:

r - 逆矩阵中的误差

r - 如何在 R testthat 中同时测试消息和错误消息?

c - 如何使用c代码打开vi编辑器读取并在一段时间后关闭

c - 生成AVL树的 key

c - 显示标准错误消息

java - Jackson @JsonCreator 无法识别的属性

C编程二维数组malloc : Interesting values after every row. 求解释

java - 强制 JAX-RS 将我的类序列化为 JSON 对象

angularjs - Laravel 和 json 数组

R:从一个数据帧制作多个分类散点图