Converts R objects to JSON
to_json(
x,
unbox = FALSE,
digits = NULL,
numeric_dates = TRUE,
factors_as_string = TRUE,
by = "row"
)
object to convert to JSON
logical indicating if single-value arrays should be 'unboxed', that is, not contained inside an array.
integer specifying the number of decimal places to round numerics.
Default is NULL
- no rounding
logical indicating if dates should be treated as numerics. Defaults to TRUE for speed. If FALSE, the dates will be coerced to character in UTC time zone
logical indicating if factors should be treated as strings. Defaults to TRUE.
either "row" or "column" indicating if data.frames and matrices should be processed row-wise or column-wise. Defaults to "row"
to_json(1:3)
#> [1,2,3]
to_json(letters[1:3])
#> ["a","b","c"]
## factors treated as strings
to_json(data.frame(x = 1:3, y = letters[1:3], stringsAsFactors = TRUE ))
#> [{"x":1,"y":"a"},{"x":2,"y":"b"},{"x":3,"y":"c"}]
to_json(data.frame(x = 1:3, y = letters[1:3], stringsAsFactors = FALSE ))
#> [{"x":1,"y":"a"},{"x":2,"y":"b"},{"x":3,"y":"c"}]
to_json(list(x = 1:3, y = list(z = letters[1:3])))
#> {"x":[1,2,3],"y":{"z":["a","b","c"]}}
to_json(seq(as.Date("2018-01-01"), as.Date("2018-01-05"), length.out = 5))
#> [17532.0,17533.0,17534.0,17535.0,17536.0]
to_json(seq(as.Date("2018-01-01"), as.Date("2018-01-05"), length.out = 5), numeric_dates = FALSE)
#> ["2018-01-01","2018-01-02","2018-01-03","2018-01-04","2018-01-05"]
psx <- seq(
as.POSIXct("2018-01-01", tz = "Australia/Melbourne"),
as.POSIXct("2018-02-01", tz = "Australia/Melbourne"),
length.out = 5
)
to_json(psx)
#> [1514725200,1515394800,1516064400,1516734000,1517403600]
to_json(psx, numeric_dates = FALSE)
#> ["2017-12-31T13:00:00","2018-01-08T07:00:00","2018-01-16T01:00:00","2018-01-23T19:00:00","2018-01-31T13:00:00"]
## unbox single-value arrays
to_json(list(x = 1), unbox = TRUE)
#> {"x":1.0}
to_json(list(x = 1, y = c("a"), z = list(x = 2, y = c("b"))), unbox = TRUE)
#> {"x":1.0,"y":"a","z":{"x":2.0,"y":"b"}}
## rounding numbers using the digits argument
to_json(1.23456789, digits = 2)
#> [1.23]
df <- data.frame(x = 1L:3L, y = rnorm(3), z = letters[1:3], stringsAsFactors = TRUE )
to_json(df, digits = 0 )
#> [{"x":1,"y":3.0,"z":"a"},{"x":2,"y":1.0,"z":"b"},{"x":3,"y":-0.0,"z":"c"}]
## keeping factors
to_json(df, digits = 2, factors_as_string = FALSE )
#> [{"x":1,"y":2.69,"z":1},{"x":2,"y":0.56,"z":2},{"x":3,"y":-0.02,"z":3}]