1
我想從TSV列中提取JSON。難度在於JSON是淺層嵌套的,並且鍵值可能不會出現在每一行中。從R數據框中提取嵌套的JSON而不知道鍵
我有一個最小的例子來說明我的觀點。
df <- tibble(index = c(1, 2),
data = c('{"json_char":"alpha", "json_list1":["x","y"]}',
'{"json_char":"beta", "json_list1":["x","y","z"], "json_list2":["a","b","c"]}'))
期望的結果:
df <- tibble::tibble(index = list(1, 2),
json_char = list("alpha", "beta"),
json_list1 = list(list("x","y"), list("x","y","z")),
json_list2 = list(NA, list("a","b","c")))
了相當數量的實驗之後,我有這樣的功能:
extract_json_column <- function(df) {
df %>%
magrittr::use_series(data) %>%
purrr::map(jsonlite::fromJSON) %>%
purrr::map(purrr::simplify) %>%
tibble::enframe() %>%
tidyr::spread("name", "value") %>%
purrr::flatten_dfr()
}
使我有以下錯誤:Error in bind_rows_(x, .id) : Argument 2 must be length 3, not 7
。
第一行設置其餘數據幀的參數數量。無論如何要避免這種行爲?