toJSON() serializes R objects to JSON text. It has
methods for common base R types and can be extended with S4 methods.
toJSON(c(1, 2, 3))
#> [1] "[ 1, 2, 3 ]"
toJSON(c(TRUE, FALSE))
#> [1] "[ true, false ]"
toJSON(c("abc", "xyz"))
#> [1] "[ \"abc\", \"xyz\" ]"Named atomic vectors are written as JSON objects.
Lists can represent nested JSON objects and arrays.
By default, data frames are serialized by column. Use
byrow = TRUE to write a row-oriented array.
data <- data.frame(id = 1:2, label = c("a", "b"))
cat(toJSON(data, pretty = TRUE))
#> {
#> "id" : [
#> 1,
#> 2
#> ],
#> "label" : [
#> "a",
#> "b"
#> ]
#> }
cat(toJSON(data, byrow = TRUE, colNames = TRUE, pretty = TRUE))
#> [
#> {
#> "id" : 1,
#> "label" : "a"
#> },
#> {
#> "id" : 2,
#> "label" : "b"
#> }
#> ]Missing values are written as JSON null by default.
Empty unnamed lists are written as arrays, while
emptyNamedList is written as an object.