R将Json输出转换为数据帧

问题描述:

我试图将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://*.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Deena

看起来好像其中一个问题是由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数据。 –