Debian Codegraph @

R/json.R

raw
1 #' A simple JSON serializer
2 #'
3 #' A JSON serializer that only works on a limited types of R data (`NULL`,
4 #' lists, arrays, logical/character/numeric/date/time vectors). Other types of
5 #' data will be coerced to character. A character string
6 #' wrapped in `js()` is treated as raw JavaScript, so will not be quoted. The
7 #' function `json_vector()` converts an atomic R vector to JSON.
8 #'
9 #' Both `NULL` and `NA` are converted to `null`. Named lists are converted to
10 #' objects of the form `{key1: value1, key2: value2, ...}`. Unnamed lists are
11 #' converted to arrays of the form `[[value1], [value2], ...]`. The same rules
12 #' apply to data frames since technically they are also lists. However, please
13 #' note that unnamed data frames (i.e., without column names) will be converted
14 #' to an array with each _row_ as an array element, whereas named data frames
15 #' will have each _column_ as an individual element. For matrices, the JSON
16 #' array will have each row as an individual element, and names are discarded.
17 #'
18 #' Dates and times are coerced to character using UTC as the timezone, and
19 #' represented via the JavaScript expression `new Date(value)` (which is not
20 #' standard JSON but practically more useful).
21 #' @param x An R object.
22 #' @export
23 #' @return A character string.
24 #' @seealso The \pkg{jsonlite} package provides a full JSON serializer.
25 #' @examples library(xfun)
26 #' tojson(NULL); tojson(1:10); tojson(TRUE); tojson(FALSE)
27 #' tojson(list(a = 1, b = list(c = 1:3, d = 'abc')))
28 #' tojson(list(c('a', 'b'), 1:5, TRUE, Sys.Date() + 1:3))
29 #' tojson(head(iris)) # each column is in an element
30 #' tojson(unname(head(iris))) # each row is in an element
31 #' tojson(matrix(1:12, 3))
32 #'
33 #' # literal JS code
34 #' tojson(list(a = 1:5, b = js('function() {return true;}')))
35 tojson = function(x) {
36 if (inherits(x, 'json')) return(x)
37 res = structure(.tojson(x), class = 'json')
38 raw_string(res, lang = '.json')
39 }
40
41 .tojson = function(x, n = 1) {
42 make_array = function(..., braces = c('[', ']')) {
43 inner = paste0(strrep(' ', n), ..., collapse = ',\n')
44 paste0(braces[1], '\n', inner, '\n', strrep(' ', n - 1), braces[2])
45 }
46 if (is.null(x)) 'null' else if (is.array(x)) {
47 make_array(apply(x, 1, .tojson, n + 1))
48 } else if (is.list(x)) {
49 if (length(x) == 0) return('{}')
50 # output unnamed data frames by rows instead of columns
51 nms = names(x)
52 is_df = is.data.frame(x)
53 by_row = is_df && is.null(nms)
54 cols = unlist(lapply(x, function(z) {
55 if (by_row) json_atomic(z, FALSE) else {
56 # data frame columns must be arrays even for length 1
57 .tojson(if (is_df) I(z) else z, n + 1)
58 }
59 }))
60 if (is.null(nms)) {
61 if (by_row) {
62 dim(cols) = dim(x)
63 cols = apply(cols, 1, json_vector, TRUE, FALSE)
64 }
65 make_array(cols)
66 } else {
67 make_array(quote_string(nms), ': ', cols, braces = c('{', '}'))
68 }
69 } else if (is.character(x) && inherits(x, c('JS_LITERAL', 'JS_EVAL'))) {
70 paste(x, collapse = '\n')
71 } else json_atomic(x)
72 }
73
74 #' @rdname tojson
75 #' @export
76 js = function(x) structure(x, class = 'JS_LITERAL')
77
78 json_atomic = function(x, to_array = NA) {
79 use_quote = !(is.numeric(x) || is.logical(x))
80 asis = inherits(x, 'AsIs')
81 if (is.factor(x)) x = as.character(x)
82 if (is.logical(x)) x = tolower(as.character(x))
83 if (inherits(x, c('Date', 'POSIXct', 'POSIXt'))) {
84 if (asis) class(x) = setdiff(class(x), 'AsIs')
85 x = sprintf('new Date("%s")', format(x, tz = 'UTC'))
86 use_quote = FALSE
87 }
88 if (is.na(to_array)) to_array = length(x) != 1 || asis
89 json_vector(x, to_array, use_quote)
90 }
91
92 #' @param to_array Whether to convert a vector to a JSON array (use `[]`).
93 #' @param quote Whether to double quote the elements.
94 #' @rdname tojson
95 #' @export
96 json_vector = function(x, to_array = FALSE, quote = TRUE) {
97 i = is.na(x)
98 if (quote) {
99 x = quote_string(x)
100 x = gsub('\n', '\\\\n', x)
101 x = gsub('\b', '\\\\b', x)
102 x = gsub('\f', '\\\\f', x)
103 x = gsub('\r', '\\\\r', x)
104 x = gsub('\t', '\\\\t', x)
105 } else if (is.numeric(x)) {
106 x = ifelse(is.infinite(x), ifelse(x > 0, 'Infinity', '-Infinity'), x)
107 }
108 x[i] = 'null'
109 if (to_array) paste0('[', paste(x, collapse = ', '), ']') else x
110 }
111
112 # escape \ and " in strings, and quote them
113 quote_string = function(x) {
114 x = gsub('(["\\])', "\\\\\\1", x)
115 if (length(x)) x = paste0('"', x, '"')
116 x
117 }