#' Validate input JSON string
#'
#' This function validates JSON in 2 steps:
#' 1) Checks if all required keys are present
#' 2) Checks if all values are not NULL
#' If any of above conditions is not fulfilled, an error is throwed
#'
#' @param x JSON character string
#' @param requiredKeys character vector, names of keys that are required in x
#'
#' @return R list, converted from JSON
#' @export
validateInputJson <- function(x, requiredKeys = c()){
x <- jsonlite::fromJSON(
txt = x,
simplifyVector = FALSE
)
requiredKeysAvailable <- requiredKeys %in% names(x)
if (any(!requiredKeysAvailable)){
notProvidedKeys <- requiredKeys[!requiredKeysAvailable]
stop(
"The following keys are not provided: ",
paste(notProvidedKeys, collapse = ", ")
)
}
isNullValueKey <- sapply(
X = x,
FUN = is.null
)
if (any(isNullValueKey)){
nullValueKeys <- names(x)[isNullValueKey]
stop(
"The following keys contain NULL values: ",
paste(nullValueKeys, collapse = ", ")
)
}
x
}
#' Get default option parser
#'
#' Returns default option parser, which is useful in Rscript mode. The parser
#' handles one character input argument: "-j", which should be a JSON string.
#' Parsed argument will be named "json" in the output list.
#'
#' @param ... Additional optparse::make_option(s) to be included in parser
#'
#' @return OptionParser-class object
#' @export
getDefaultOptionParser <- function(...){
optparse::OptionParser(
option_list = list(
optparse::make_option(
opt_str = c("-j", "--json"),
type = "character",
default = NULL,
help = "JSON input string",
metavar = "character"
),
...
)
)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.