问题
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