Skip to content

The function cereal_to_json() serializes the vctrs prototype of a data frame to JSON, and the function cereal_from_json() deserializes from a JSON prototype back to a vctrs prototype.

Usage

cereal_to_json(data)

cereal_from_json(x)

Arguments

data

A data frame

x

A JSON string

Value

cereal_to_json() returns a JSON string like jsonlite::toJSON(), and cereal_from_json() returns a vctrs ptype, like vctrs::vec_ptype().

Examples


df <- tibble::tibble(
    a = 1,
    b = 2L,
    c = Sys.Date(),
    d = as.POSIXct("2019-01-01", tz = "America/New_York"),
    e = "x",
    f = factor("blue", levels = c("blue", "green", "red")),
    g = ordered("small", levels = c("small", "medium", "large"))
)

json <- cereal_to_json(df)
json
#> {
#>   "a": {
#>     "type": "numeric",
#>     "example": "1",
#>     "details": []
#>   },
#>   "b": {
#>     "type": "integer",
#>     "example": "2",
#>     "details": []
#>   },
#>   "c": {
#>     "type": "Date",
#>     "example": "2023-06-09",
#>     "details": []
#>   },
#>   "d": {
#>     "type": "POSIXct",
#>     "example": "2019-01-01",
#>     "details": {
#>       "tzone": "America/New_York"
#>     }
#>   },
#>   "e": {
#>     "type": "character",
#>     "example": "x",
#>     "details": []
#>   },
#>   "f": {
#>     "type": "factor",
#>     "example": "blue",
#>     "details": {
#>       "levels": ["blue", "green", "red"]
#>     }
#>   },
#>   "g": {
#>     "type": "ordered",
#>     "example": "small",
#>     "details": {
#>       "levels": ["small", "medium", "large"]
#>     }
#>   }
#> } 

str(cereal_from_json(json))
#> tibble [0 × 7] (S3: tbl_df/tbl/data.frame)
#>  $ a: num(0) 
#>  $ b: int(0) 
#>  $ c: 'Date' num(0) 
#>  $ d: 'POSIXct' num(0) 
#>  - attr(*, "tzone")= chr "America/New_York"
#>  $ e: chr(0) 
#>  $ f: Factor w/ 3 levels "blue","green",..: 
#>  $ g: Ord.factor w/ 3 levels "small"<"medium"<..: 
## same as:
str(vctrs::vec_ptype(df))
#> tibble [0 × 7] (S3: tbl_df/tbl/data.frame)
#>  $ a: num(0) 
#>  $ b: int(0) 
#>  $ c: 'Date' num(0) 
#>  $ d: 'POSIXct' num(0) 
#>  - attr(*, "tzone")= chr "America/New_York"
#>  $ e: chr(0) 
#>  $ f: Factor w/ 3 levels "blue","green",..: 
#>  $ g: Ord.factor w/ 3 levels "small"<"medium"<..: