Skip to contents

Prepares an object of arrays.

Usage

prep_data(x)

Arguments

x

named vector, list, or data frame

Value

List of formatted objects

Details

Note that unboxing will only work on items where you have 1:1 key value pair. So if you have a dataframe with multiple rows or a list with multiple values at a given position, it won't work.

Examples


cars_small  <- datasets::cars[1:10,]

# creates an array of objects where each
# row is an object
cars_small |>
  jsonlite::toJSON(pretty = TRUE)
#> [
#>   {
#>     "speed": 4,
#>     "dist": 2
#>   },
#>   {
#>     "speed": 4,
#>     "dist": 10
#>   },
#>   {
#>     "speed": 7,
#>     "dist": 4
#>   },
#>   {
#>     "speed": 7,
#>     "dist": 22
#>   },
#>   {
#>     "speed": 8,
#>     "dist": 16
#>   },
#>   {
#>     "speed": 9,
#>     "dist": 10
#>   },
#>   {
#>     "speed": 10,
#>     "dist": 18
#>   },
#>   {
#>     "speed": 10,
#>     "dist": 26
#>   },
#>   {
#>     "speed": 10,
#>     "dist": 34
#>   },
#>   {
#>     "speed": 11,
#>     "dist": 17
#>   }
#> ] 

# creates an object with 2 arrays
prep_object(cars_small) |>
  jsonlite::toJSON(pretty = TRUE)
#> {
#>   "speed": [4, 4, 7, 7, 8, 9, 10, 10, 10, 11],
#>   "dist": [2, 10, 4, 22, 16, 10, 18, 26, 34, 17]
#> } 

# this makes no difference
x <- list("hello" = 1:10, "world" = "Earth")

prep_object(x) |>
  jsonlite::toJSON(pretty = TRUE)
#> {
#>   "hello": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
#>   "world": ["Earth"]
#> }