【问题标题】:When using jsonlite in R, how do I specify that only some of the entries are to be treated as arrays?在 R 中使用 jsonlite 时,如何指定仅将某些条目视为数组?
【发布时间】:2018-11-22 06:43:06
【问题描述】:

我有以下代码:

# 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 中的一些参数,但似乎无法正确使用。

【问题讨论】:

    标签: r serialization jsonlite


    【解决方案1】:

    auto_unbox=TRUE 的论点成功了:

    自动拆箱所有长度为 1 的原子向量。避免这种情况通常更安全,而是使用拆箱功能拆箱单个元素。一个例外 是 AsIs 类的对象(即包装在 I() 中)不会自动拆箱。这是一种将单个值标记为长度为 1 的数组的方法。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      相关资源
      最近更新 更多