R将Json读入data.frame

时间:2018-01-11 03:52:05

标签: json r dataframe rbind

我正在尝试将json文件加载到data.frame中的R。但是我的数据中有一些list()为空。

以下是我的json数据:

json_file1 <- jsonlite::fromJSON('{"txtId":"20180101","data":{"user":[{"id":"123","phone":"00001","realName":"Eric","addr":{},"source":{},"registerDate":{},"type":0,"remain":{}}],"score":[]}}')
json_file2 <- jsonlite::fromJSON('{"txtId":"20180102","data":{"user":[{"id":"456","phone":"00002","realName":"Amy","addr":{},"source":{},"registerDate":{},"type":0,"remain":100}],"score":[]}}')
json_file = list(json_file1, json_file2)
zt.detail = lapply(json_file, function(y){
  if(!is.null(y$data$user)) data.frame(y$data$user, stringsAsFactors = F)
  })

当我rbind zt.detail时,我收到错误:

# > dat_callrecord = data.table::rbindlist(zt.detail, fill = T)
# Error in data.table::rbindlist(zt.detail, fill = T) : 
#   Column 4 of item 1 is length 0, inconsistent with first column of that item which is length 1. rbind/rbindlist doesn't recycle as it already expects each item to be a uniform list, data.frame or data.table
# > str(zt.detail[[1]])
# 'data.frame': 1 obs. of  9 variables:
#   $ id          : chr "123"
# $ phone       : chr "00001"
# $ realName    : chr "Eric"
# $ addr        :'data.frame':  1 obs. of  0 variables
# $ source      :'data.frame':  1 obs. of  0 variables
# $ registerDate:'data.frame':  1 obs. of  0 variables
# $ type        : int 0
# $ remain      :'data.frame':  1 obs. of  0 variables

错误是由于我的数据结构包含1个观察值data.frame但0个变量引起的。因此,我希望之前将list()转移到NA并获得以下结果:

> dat_callrecord
id phone realName type remain addr source registerDate
123 00001  Eric    0    NA     NA     NA    NA      
456 00002  Amy     0    100    NA     NA    NA

1 个答案:

答案 0 :(得分:3)

我们可以遍历import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity,如果有list,请将其替换为data.frame,然后执行NA

rbindlist