通过使用 jsonlite 转换包含大量数字的 json 字符串得到错误的结果
get wrong result by converting json string containing large number by using jsonlite
这是 MWE,如何获取正确的数字作为字符。
require(jsonlite)
j <- "{\"id\": 323907258301939713}"
a <- fromJSON(j)
print(a$id, digits = 20)
class(a$id)
a$id <- as.character(a$id)
a$id
class(a$id)
这是输出。
Loading required package: jsonlite
Loading required package: methods
[1] 323907258301939712
[1] "numeric"
[1] "323907258301939712"
[1] "character"
我想得到 323907258301939713
作为 a
中字符的确切数字
在JavaScript中,数字是双精度浮点数,即使它们看起来像整数,所以它们只有大约 16 位十进制数字的精度。特别是 JavaScript 代码:
console.log(12345678901234567 == 12345678901234568)
打印 "true".
JSON 标准从 JavaScript 继承了此限制,因此 jsonlite
实际上通过将数字读取为双精度来正确解释您的 JSON。
因为这实际上是 JSON 标准的一个限制,如果您可以控制生成 JSON 的程序,如果您修复您的 JSON(例如,将 id
属性表示为字符串):
{ "id": "323907258301939713" }
但是,如果您绝对必须解析这个格式错误的 JSON,那么您很幸运。 fromJSON
函数采用未记录的布尔参数 bigint_as_char
将这些大数字作为字符值读入 R:
> a <- fromJSON(j, bigint_as_char=TRUE)
> print(a$id)
[1] "323907258301939713"
>
但是,您必须准备好处理其余 R 代码中的纯数字和字符值,因为 fromJSON
仍将正常读取 small 整数数字,只将这些太大的整数作为字符串读取。
这是 MWE,如何获取正确的数字作为字符。
require(jsonlite)
j <- "{\"id\": 323907258301939713}"
a <- fromJSON(j)
print(a$id, digits = 20)
class(a$id)
a$id <- as.character(a$id)
a$id
class(a$id)
这是输出。
Loading required package: jsonlite
Loading required package: methods
[1] 323907258301939712
[1] "numeric"
[1] "323907258301939712"
[1] "character"
我想得到 323907258301939713
作为 a
在JavaScript中,数字是双精度浮点数,即使它们看起来像整数,所以它们只有大约 16 位十进制数字的精度。特别是 JavaScript 代码:
console.log(12345678901234567 == 12345678901234568)
打印 "true".
JSON 标准从 JavaScript 继承了此限制,因此 jsonlite
实际上通过将数字读取为双精度来正确解释您的 JSON。
因为这实际上是 JSON 标准的一个限制,如果您可以控制生成 JSON 的程序,如果您修复您的 JSON(例如,将 id
属性表示为字符串):
{ "id": "323907258301939713" }
但是,如果您绝对必须解析这个格式错误的 JSON,那么您很幸运。 fromJSON
函数采用未记录的布尔参数 bigint_as_char
将这些大数字作为字符值读入 R:
> a <- fromJSON(j, bigint_as_char=TRUE)
> print(a$id)
[1] "323907258301939713"
>
但是,您必须准备好处理其余 R 代码中的纯数字和字符值,因为 fromJSON
仍将正常读取 small 整数数字,只将这些太大的整数作为字符串读取。