2016-07-25 83 views
0

我試圖將Json輸出轉換爲數據幀。 JSON的輸出如下R將Json輸出轉換爲數據幀

[[1]] 
[[1]]$id 
[1] "176248" 

[[1]]$report_list_id 
[[1]]$report_list_id[[1]] 
[1] "183556" 


[[1]]$name 
[1] "Torchy's Tacos" 


[[2]] 
[[2]]$id 
[1] "180642" 

[[2]]$report_list_id 
[[2]]$report_list_id[[1]] 
[1] "188160" 


[[2]]$name 
[1] "CircusTrix" 

,我使用如下

library(jsonlite) 
library(httr) 
library(RJSONIO) 
x= content(dash)$data 
xx <- data.frame(do.call(rbind, x)) 

但是代碼,這段代碼不能選擇不公開某些列,並將所得DF看起來是這樣的。

id 
report_list_id 
name 
1 
176248 
list("183556") 
Torchy's Tacos 
2 
180642 
list("188160") 
CircusTrix 

有沒有更好的方法來將Json轉換爲DF,以避免這些問題。

+0

可以添加您的JSON輸出的'dput'結果嗎? – Deena

+0

@Dee我不太確定dput結果的含義。將Json轉換爲DF的最佳方法是什麼? – rrodrigorn0

+0

http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Deena

回答

0

看起來好像其中一個問題是由JSON解析到列表引起的,因爲結果輸出是列表列表(即嵌套結構)。

例如,[[1]]$report_list_id[[1]]意味着列表元素#1具有名爲$report_list_id的元件,其與第一(和唯一元件)的列表具有值"183556"

在您處理嵌套列表後,您需要將每個列表元素轉換爲data.frame,然後將這些行綁定在一起(在您的代碼中綁定行然後轉換爲data.frame)。

編輯 - 這裏就是我的意思:

# original data structure (with nested list) 
the_list <- list(list('id' = "176248", 'report_list_id' = list("183556"), 'name' = "Torchy's Tacos"), 
       list('id' = "180642", 'report_list_id' = list("188160"), 'name' = "CircusTrix")) 

# convert each 'row/document' of data (i.e. element in the top-level list) into a data frame, 
# taking care to un-nest the 'report_list_id' field 
list_of_data_frame_rows <- lapply(X = the_list, 
            FUN = function(x) { data.frame('id' = x$id, 'report_list_id' = x$report_list_id[[1]], 'name' = x$name) }) 

# combine rows into a single data.frame 
# (note: this is slow for many rows - 'bind_rows(...)' in the dplyr package is a safer bet) 
combined_data_frame <- do.call(rbind, list_of_data_frame_rows) 

combined_data_frame 
# id  report_list_id name 
# 1 176248 183556   Torchy's Tacos 
# 2 180642 188160   CircusTrix 
+0

你如何建議我這樣做。我應該有我的代碼 - df = rbind(do.call(unlist,x)) – rrodrigorn0

+0

請參閱我的編輯。將來可以看到原始的JSON數據。 –