【问题标题】:From list of json files to data.table: partial variable list从 json 文件列表到 data.table:部分变量列表
【发布时间】:2017-04-22 23:37:15
【问题描述】:

我有一个包含 100,000 多个 json 文件的列表,我想从中获取一个只有几个变量的 data.table。不幸的是,这些文件很复杂。每个json文件的内容如下:

示例 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

【问题讨论】:

    标签: json r data.table jsonlite


    【解决方案1】:

    从错误消息中,我想这基本上意味着 mclapply() 的结果之一是空的,空我的意思是 NULL 或具有 0 行的 data.table,或者只是在并行处理中遇到错误。

    你可以做的是:

    1. 在 mclapply() 中添加更多检查,例如尝试错误或检查 b 的类和 b 的 nrow,是否 b 为空

    2. 使用rbindlist时,添加参数fill = T

    希望这能解决你的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 2019-07-06
      • 2015-03-31
      • 2016-03-13
      • 2019-04-07
      • 1970-01-01
      相关资源
      最近更新 更多