A JSON serializer that only works on a limited types of R data (NULL,
lists, arrays, logical/character/numeric/date/time vectors). Other types of
data will be coerced to character. A character string
wrapped in js() is treated as raw JavaScript, so will not be quoted. The
function json_vector() converts an atomic R vector to JSON.
Details
Both NULL and NA are converted to null. Named lists are converted to
objects of the form {key1: value1, key2: value2, ...}. Unnamed lists are
converted to arrays of the form [[value1], [value2], ...]. The same rules
apply to data frames since technically they are also lists. However, please
note that unnamed data frames (i.e., without column names) will be converted
to an array with each row as an array element, whereas named data frames
will have each column as an individual element. For matrices, the JSON
array will have each row as an individual element, and names are discarded.
Dates and times are coerced to character using UTC as the timezone, and
represented via the JavaScript expression new Date(value) (which is not
standard JSON but practically more useful).
Examples
library(xfun)
tojson(NULL)
#> null
tojson(1:10)
#> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tojson(TRUE)
#> true
tojson(FALSE)
#> false
tojson(list(a = 1, b = list(c = 1:3, d = "abc")))
#> {
#> "a": 1,
#> "b": {
#> "c": [1, 2, 3],
#> "d": "abc"
#> }
#> }
tojson(list(c("a", "b"), 1:5, TRUE, Sys.Date() + 1:3))
#> [
#> ["a", "b"],
#> [1, 2, 3, 4, 5],
#> true,
#> [new Date("2026-07-03"), new Date("2026-07-04"), new Date("2026-07-05")]
#> ]
tojson(head(iris)) # each column is in an element
#> {
#> "Sepal.Length": [5.1, 4.9, 4.7, 4.6, 5, 5.4],
#> "Sepal.Width": [3.5, 3, 3.2, 3.1, 3.6, 3.9],
#> "Petal.Length": [1.4, 1.4, 1.3, 1.5, 1.4, 1.7],
#> "Petal.Width": [0.2, 0.2, 0.2, 0.2, 0.2, 0.4],
#> "Species": ["setosa", "setosa", "setosa", "setosa", "setosa", "setosa"]
#> }
tojson(unname(head(iris))) # each row is in an element
#> [
#> [5.1, 3.5, 1.4, 0.2, "setosa"],
#> [4.9, 3, 1.4, 0.2, "setosa"],
#> [4.7, 3.2, 1.3, 0.2, "setosa"],
#> [4.6, 3.1, 1.5, 0.2, "setosa"],
#> [5, 3.6, 1.4, 0.2, "setosa"],
#> [5.4, 3.9, 1.7, 0.4, "setosa"]
#> ]
tojson(matrix(1:12, 3))
#> [
#> [1, 4, 7, 10],
#> [2, 5, 8, 11],
#> [3, 6, 9, 12]
#> ]
# literal JS code
tojson(list(a = 1:5, b = js("function() {return true;}")))
#> {
#> "a": [1, 2, 3, 4, 5],
#> "b": function() {return true;}
#> }