在 R 中使用 jsonlite 时,如何指定仅将某些条目视为数组? [英] When using jsonlite in R, how do I specify that only some of the entries are to be treated as arrays?

查看:37
本文介绍了在 R 中使用 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]}

我尝试使用 文档,但似乎做对了.

I've tried using some of the parameters from the documentation, but can't seem to get it right.

推荐答案

参数 auto_unbox=TRUE 成功了:

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

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),它返回我所期望的:

I.e., the solution was toJSON(x, auto_unbox=TRUE), which returns what I expected:

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

这篇关于在 R 中使用 jsonlite 时,如何指定仅将某些条目视为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆