When using jsonlite in R, how do I specify that only some of the entries are to be treated as arrays?

有些话、适合烂在心里 提交于 2019-12-20 03:11:56

问题


I have the following code:

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

This prints:

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

I was expecting:

{"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.


回答1:


The argument auto_unbox=TRUE did the trick:

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.

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

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


来源:https://stackoverflow.com/questions/53425221/when-using-jsonlite-in-r-how-do-i-specify-that-only-some-of-the-entries-are-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!