Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 285
André C. Andersen Avatar asked Sep 06 '25 02:09

André C. Andersen


1 Answers

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]}
like image 139
André C. Andersen Avatar answered Sep 07 '25 22:09

André C. Andersen