2017-04-22 72 views
0

我有一個超過100,000個json文件的列表,我想從中獲取data.table只有幾個變量。不幸的是這些文件很複雜。每個JSON文件的內容是這樣的:從json文件列表到data.table:部分變量列表

樣品1

$id 
[1] "10.1" 
$title 
$title$value 
[1] "Why this item" 
$itemsource 
$itemsource$id 
[1] "AA" 
$date 
[1] "1992-01-01" 
$itemType 
[1] "art" 
$creators 
list() 

樣品2

$id 
[1] "10.2" 
$title 
$title$value 
[1] "We need this item" 
$itemsource 
$itemsource$id 
[1] "AY" 
$date 
[1] "1999-01-01" 
$itemType 
[1] "art" 
$creators 
    type    name firstname surname affiliationIds 
1 Person Frank W. Cornell. Frank W. Cornell.    a1 
2 Person David A. Chen. David A. Chen.    a1 

$affiliations 
    id           name 
1 a1 Foreign Affairs Desk, New York Times 

我從這組文件需要與製作者姓名,項目ID和日期表。對於上述兩個示例文件:

id   date   name    firstname lastname creatortype 
"10.1"  "1992-01-01"  NA     NA  NA  NA 
"10.2"  "1999-01-01" Frank W. Cornell.  Frank W. Cornell. Person 
"10.2"  "1999-01-01" David A. Chen.   David A. Chen.  Person 

我迄今所做的:

library(parallel) 
library(data.table) 
library(jsonlite) 
library(dplyr) 

filelist = list.files(pattern="*.json",recursive=TRUE,include.dirs =TRUE) 
parsed = mclapply(filelist, function(x) fromJSON(x),mc.cores=24) 
data = rbindlist(mclapply(1:length(parsed), function(x) { 
    a = data.table(item = parsed[[x]]$id, date = list(list(parsed[[x]]$date)), name = list(list(parsed[[x]]$name)), creatortype = list(list(parsed[[x]]$creatortype))) #ignoring the firstname/lastname fields here for convenience 
    b = data.table(id = a$item, date = unlist(a$date), name=unlist(a$name), creatortype=unlist(a$creatortype)) 
    return(b) 
},mc.cores=24)) 

然而,在最後一步,我得到這個錯誤:

"Error in rbindlist(mclapply(1:length(parsed), function(x){: 
Item 1 of list is not a data.frame, data.table or list" 

在此先感謝爲您的建議。 相關的問題包括: Extract data from list of lists [R] R convert json to list to data.table I want to convert JSON file into data.table in r How can read files from directory using R? Convert R data table column from JSON to data table

回答

1

從該錯誤消息,我想這基本上意味着,從mclapply結果之一()是空的,由空我的意思是NULL或數據。表中有0行,或者只是在並行處理中遇到錯誤。

你可以做的是:

  1. 添加更多的檢查mclapply內()之類的嘗試 - 錯誤或檢查B類B和nrow的,B是否爲空或不

  2. 當你使用rbindlist,添加參數填充= T

希望這可以解決你的問題。