R/utils-microservice.R

Defines functions unserialize_json_to_df serialize_df_to_json

# Serializes -------------------------------------------------------------
#' @title Serialize a data.frame into JSON strings
#' @param df (`data.frame`) Data to serialize
#' @details One JSON string for each data.frame row
#' @family microservice utilities
#' @keywords internal
#' @export
#' @examples
#' # Convert [NxM] data.frame into [Nx1] character vector
#' mtcars_json <- serialize_df_to_json(mtcars)
#' stopifnot(identical(typeof(mtcars_json), "character"))
#' stopifnot(identical(length(mtcars_json), nrow(mtcars)))
#' head(mtcars_json)
serialize_df_to_json <- function(df){
    stopifnot(is.data.frame(df))
    invisible(
        df
        %>% purrr::pmap_dfr(function(...){
            data.frame(...) %>%
                jsonlite::toJSON(dataframe = "rows", auto_unbox = !FALSE, na = "string", pretty = FALSE) %>%
                as.character() %>%
                as.data.frame()
        })
        %>% .[[1]]
    )
}

#' @title Serialize JSON strings into a data.frame
#' @param json (`character`) Character vector that comprises JSON strings
#' @details One data.frame row for each JSON string
#' @family microservice utilities
#' @keywords internal
#' @export
#' @examples
#' # Convert [NxM] data.frame into [Nx1] character vector
#' mtcars_json <- mtcars %>% serialize_df_to_json()
#' head(mtcars_json)
#'
#' # Convert [Nx1] character vector into [NxM] data.frame
#' mtcars_df <- mtcars_json %>% unserialize_json_to_df()
#' head(mtcars_df)
#'
#' # Tests
#' stopifnot(identical(length(mtcars_json), nrow(mtcars_df)))
unserialize_json_to_df <- function(json){
    stopifnot(is.character(json))
    json %>% purrr::map_df(jsonlite::fromJSON)
}
harell/microservices documentation built on March 2, 2021, 3:15 a.m.