Last active
November 18, 2022 11:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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