Skip to content

Instantly share code, notes, and snippets.

@long39ng
Last active November 18, 2022 11:35
Show Gist options
  • Save long39ng/75deda82ef9618806a5aa75d0c038440 to your computer and use it in GitHub Desktop.
Save long39ng/75deda82ef9618806a5aa75d0c038440 to your computer and use it in GitHub Desktop.
Unnest fields from a JSON/JSONB column to new columns in a PostgreSQL database table
#' Unnest fields from a JSON/JSONB column in a PostgreSQL database table
#'
#' @inheritParams dbplyr:::select.tbl_lazy
#' @param .json_col Unquoted name of the JSONB column
#' @param ... Expressions in the syntax `<new_column_name> = "<json_field_name>"`
#'
unnest_json <- function(.data, .json_col, ...) {
.json_col <- rlang::ensym(.json_col)
col_names <- rlang::enexprs(...)
query_select_cols <- purrr::map(col_names, \(x) {
dbplyr::sql_expr(
!!.json_col %->>% !!x,
con = .data$src$con
)
})
dplyr::mutate(.data, !!!query_select_cols)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment