tojson | R Documentation |
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 of the class
JS_LITERAL
is treated as raw JavaScript, so will not be quoted. The
function json_vector()
converts an atomic R vector to JSON.
tojson(x)
json_vector(x, to_array = FALSE, quote = TRUE)
x |
An R object. |
to_array |
Whether to convert a vector to a JSON array (use |
quote |
Whether to double quote the elements. |
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).
A character string.
The jsonlite package provides a full JSON serializer.
library(xfun)
tojson(NULL)
tojson(1:10)
tojson(TRUE)
tojson(FALSE)
tojson(list(a = 1, b = list(c = 1:3, d = "abc")))
tojson(list(c("a", "b"), 1:5, TRUE, Sys.Date() + 1:3))
tojson(head(iris)) # each column is in an element
tojson(unname(head(iris))) # each row is in an element
tojson(matrix(1:12, 3))
# literal JS code
JS = function(x) structure(x, class = "JS_LITERAL")
tojson(list(a = 1:5, b = JS("function() {return true;}")))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.