| 1 |
% Generated by roxygen2: do not edit by hand |
| 2 |
% Please edit documentation in R/json.R |
| 3 |
\name{tojson} |
| 4 |
\alias{tojson} |
| 5 |
\alias{js} |
| 6 |
\alias{json_vector} |
| 7 |
\title{A simple JSON serializer} |
| 8 |
\usage{ |
| 9 |
tojson(x) |
| 10 |
|
| 11 |
js(x) |
| 12 |
|
| 13 |
json_vector(x, to_array = FALSE, quote = TRUE) |
| 14 |
} |
| 15 |
\arguments{ |
| 16 |
\item{x}{An R object.} |
| 17 |
|
| 18 |
\item{to_array}{Whether to convert a vector to a JSON array (use \verb{[]}).} |
| 19 |
|
| 20 |
\item{quote}{Whether to double quote the elements.} |
| 21 |
} |
| 22 |
\value{ |
| 23 |
A character string. |
| 24 |
} |
| 25 |
\description{ |
| 26 |
A JSON serializer that only works on a limited types of R data (\code{NULL}, |
| 27 |
lists, arrays, logical/character/numeric/date/time vectors). Other types of |
| 28 |
data will be coerced to character. A character string |
| 29 |
wrapped in \code{js()} is treated as raw JavaScript, so will not be quoted. The |
| 30 |
function \code{json_vector()} converts an atomic R vector to JSON. |
| 31 |
} |
| 32 |
\details{ |
| 33 |
Both \code{NULL} and \code{NA} are converted to \code{null}. Named lists are converted to |
| 34 |
objects of the form \verb{\{key1: value1, key2: value2, ...\}}. Unnamed lists are |
| 35 |
converted to arrays of the form \verb{[[value1], [value2], ...]}. The same rules |
| 36 |
apply to data frames since technically they are also lists. However, please |
| 37 |
note that unnamed data frames (i.e., without column names) will be converted |
| 38 |
to an array with each \emph{row} as an array element, whereas named data frames |
| 39 |
will have each \emph{column} as an individual element. For matrices, the JSON |
| 40 |
array will have each row as an individual element, and names are discarded. |
| 41 |
|
| 42 |
Dates and times are coerced to character using UTC as the timezone, and |
| 43 |
represented via the JavaScript expression \verb{new Date(value)} (which is not |
| 44 |
standard JSON but practically more useful). |
| 45 |
} |
| 46 |
\examples{ |
| 47 |
library(xfun) |
| 48 |
tojson(NULL) |
| 49 |
tojson(1:10) |
| 50 |
tojson(TRUE) |
| 51 |
tojson(FALSE) |
| 52 |
tojson(list(a = 1, b = list(c = 1:3, d = "abc"))) |
| 53 |
tojson(list(c("a", "b"), 1:5, TRUE, Sys.Date() + 1:3)) |
| 54 |
tojson(head(iris)) # each column is in an element |
| 55 |
tojson(unname(head(iris))) # each row is in an element |
| 56 |
tojson(matrix(1:12, 3)) |
| 57 |
|
| 58 |
# literal JS code |
| 59 |
tojson(list(a = 1:5, b = js("function() {return true;}"))) |
| 60 |
} |
| 61 |
\seealso{ |
| 62 |
The \pkg{jsonlite} package provides a full JSON serializer. |
| 63 |
} |