r - 在 R 中使用 jsonlite 时,如何指定仅将某些条目视为数组?

标签 r serialization jsonlite

我有以下代码:

# install.packages("jsonlite")
require("jsonlite")
x = list(
    test = "my_test",
    data = c(1, 2, 3)
)
toJSON(x)

这打印:

{"test":["my_test"],"data":[1,2,3]} 

我期待:

{"test":"my_test","data":[1,2,3]}

我尝试使用 documentation 中的一些参数, 但似乎无法正确处理。

最佳答案

参数 auto_unbox=TRUE 起到了作用:

automatically unbox all atomic vectors of length 1. It is usually safer to avoid this and instead use the unbox function to unbox individual elements. An exception is that objects of class AsIs (i.e. wrapped in I()) are not automatically unboxed. This is a way to mark single values as length-1 arrays.

即,解决方案是 toJSON(x, auto_unbox=TRUE),它返回我预期的结果:

{"test":"my_test","data":[1,2,3]}

关于r - 在 R 中使用 jsonlite 时,如何指定仅将某些条目视为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53425221/

相关文章:

python - 有没有更有效的方法来枚举 python 或 R 中离散随机变量的每个可能结果的概率?

r - 如何使用 R 在 Postgresql 中编写此 json 对象

R:通过 cyphr 加密字符串,发送到 JSON,然后从 JS 转换回字符串会导致问题

JSON到R中的数据框

r - R中此功能的逻辑是什么?

在 R 或 SAS 中重新定义和合并两个表

r - .bib 文件中的 knitr block

c# - WPF : Can BinaryFormatter serialize FlowDocument instance?

java - 压缩 SHA-256 哈希

java - 如何将 Java 对象转换为 C++ 对象?