André C. Andersen
André C. Andersen

Reputation: 9405

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.

Upvotes: 4

Views: 501

Answers (1)

André C. Andersen
André C. Andersen

Reputation: 9405

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]}

Upvotes: 4

Related Questions