从R中的JSON文件获取数据

时间:2015-11-27 13:21:06

标签: json r

假设我有以下json文件:

{
  "id": "000018ac-04ef-4270-81e6-9e3cb8274d31",
   "currentCompany": "",
   "currentTitle": "--",
   "currentPosition": ""
}

我使用以下代码:

Usersfile <- ('trial.json') #where trial the json above
library('rjson')
c <- file(Usersfile,'r')
l <- readLines(c,-71L)
json <- lapply(X=l,fromJSON)

我有以下错误:

Error: parse error: premature EOF
                                   {
                 (right here) ------^

但是当我输入json文件(带记事本)并将数据放在一行时:

{"id": "000018ac-04ef-4270-81e6-9e3cb8274d31","currentCompany": "","currentTitle": "--","currentPosition": ""}

代码工作正常。(实际上,每个行手动执行文件非常大)。为什么会这样?我怎么能克服这个?

这个也不起作用:

{ "id": "000018ac-04ef-4270-81e6-9e3cb8274d31","currentCompany": "","currentTitle": "--","currentPosition": ""
}

编辑:我使用了以下代码,我只能读取第一个值:

library('rjson')
c <- file.path(Usersfile)
data <- fromJSON(file=c)

1 个答案:

答案 0 :(得分:9)

感到惊讶,这从未得到过回答!使用jsonlite包,您可以使用paste(x, collapse="")将json数据折叠为一个字符元素,从而删除EOF标记以正确导入R数据帧。我也面对一个漂亮的印刷json,确切的错误:

library(jsonlite)

json <- do.call(rbind, 
                lapply(paste(readLines(Usersfile, warn=FALSE),
                             collapse=""), 
                       jsonlite::fromJSON))