R/jsontab.R

#===============================================================================
# jsontab.R
#===============================================================================

# Imports ======================================================================

#' @import jsonlite




# Functions ====================================================================

#' @title Load a file that may be in either JSON or tabular format
#'
#' @description Regardless of the input format, a list will be returned
#'
#' @param txt a JSON string, a URL, or a JSON or tabular file
#' @param json indicates JSON input
#' @param tab indicates tabular input
#' @param ... additional arguments to be passed to \code{fromJSON} or
#'   \code{read.table}
#' @return a list representing the input data
#' @export
#' @seealso \code{\link{simplify_data_frames}}
from_json_or_tab <- function(
  txt, 
  json = FALSE, 
  tab = FALSE,
  header = FALSE,
  stringsAsFactors = TRUE,
  ...
) {
  if (json && !tab) {
    fromJSON(txt, ...)
  } else if (tab && !json) {
    list(
      as.list(
        read.table(
          txt,
          header = header,
          stringsAsFactors = stringsAsFactors,
          ...
        )
      )
    )
  } else {
    tryCatch(
      fromJSON(txt, ...),
      error = function(e) {
        list(
          as.list(
            read.table(
              txt,
              header = header,
              stringsAsFactors = stringsAsFactors,
              ...
            )
          )
        )
      }
    )
  }
}

#' @title Simplify data frames in input data
#'
#' @description Data loaded using \code{from_json_or_tab} will be parsed
#' as a list of lists. This function accepts a list generated by
#' \code{from_json_or_tab} and returns a list of data frames.
#'
#' @param x a list of lists to be converted to a list of data frames.
#' @param stringsAsFactors logical: should character vectors be converted to
#'   factor vectors?
#' @return a list of data frames
#' @export
#' @seealso \code{\link{from_json_or_tab}}
simplify_data_frames <- function(x, stringsAsFactors = TRUE) {
  lapply(x, as.data.frame, stringsAsFactors = stringsAsFactors)
}
anthony-aylward/jsontab documentation built on May 6, 2019, 11:25 a.m.