2017-10-10 46 views
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

第一行設置其餘數據幀的參數數量。無論如何要避免這種行爲?

回答

0

我將您的功能修改爲以下內容。我希望這有幫助。

library(tidyverse) 
library(rjson) 

extract_json_column <- function(df){ 
    df %>% 
    rowwise() %>% 
    mutate(data = map(data, fromJSON)) %>% 
    split(.$index) %>% 
    map(~.$data[[1]]) %>% 
    map(~map_if(., function(x) length(x) != 1, list)) %>% 
    map(as_data_frame) %>% 
    bind_rows(.id = "index") 
} 

extract_json_column(df) 
# A tibble: 2 x 4 
    index json_char json_list1 json_list2 
    <chr>  <chr>  <list>  <list> 
1  1  alpha <chr [2]>  <NULL> 
2  2  beta <chr [3]> <chr [3]>