Skip to contents

toJSON() serializes R objects to JSON text. It has methods for common base R types and can be extended with S4 methods.

Atomic vectors

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.

toJSON(c(a = 1, b = 2))
#> [1] "{\n \"a\":        1,\n\"b\":        2 \n}"
fromJSON(toJSON(c(a = 1, b = 2)))
#> a b 
#> 1 2

Lists and nested values

Lists can represent nested JSON objects and arrays.

value <- list(
  name = "example",
  flags = c(TRUE, FALSE),
  nested = list(x = 1, y = "two")
)

cat(toJSON(value, pretty = TRUE))
#> {
#>  "name" : "example",
#>  "flags" : [
#>      true,
#>      false
#>  ],
#>  "nested" : {
#>      "x" : 1,
#>      "y" : "two"
#>  }
#> }

Data frames

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

Matrices and arrays

mat <- matrix(1:4, nrow = 2)
cat(toJSON(mat))
#> [ [ 1, 3 ],
#> [ 2, 4 ] ]

arr <- array(1:8, dim = c(2, 2, 2))
isValidJSON(I(toJSON(arr)))
#> [1] TRUE

Missing and empty values

Missing values are written as JSON null by default. Empty unnamed lists are written as arrays, while emptyNamedList is written as an object.

toJSON(c("a", NA, "b"))
#> [1] "[ \"a\", null, \"b\" ]"
fromJSON(toJSON(c("a", NA, "b")), nullValue = NA, simplify = TRUE)
#> [1] "a" NA  "b"

toJSON(list())
#> [1] "[]"
toJSON(emptyNamedList)
#> [1] "{}"

Numeric formatting

The digits argument controls numeric formatting.

toJSON(c(pi, exp(1)), digits = 4)
#> [1] "[ 3.142, 2.718 ]"
toJSON(c(pi, exp(1)), digits = 8)
#> [1] "[ 3.1415927, 2.7182818 ]"