从R中的JSON文件获取数据 [英] Getting data from JSON file in R
问题描述
让我们说我有以下json文件:
Lets say that I have the following json file:
{
"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文件并将数据放在一行中时:
But when I enter the json file(with notepad) and put the data in one line:
{"id": "000018ac-04ef-4270-81e6-9e3cb8274d31","currentCompany": "","currentTitle": "--","currentPosition": ""}
代码工作正常(实际上,文件很大,需要手动对每一行进行处理).为什么会这样呢?我该如何克服?
The code works fine.(In reality the file is really big to do it manually for each line). Why is this happening? How can I overcome that?
这也不起作用:
{ "id": "000018ac-04ef-4270-81e6-9e3cb8274d31","currentCompany": "","currentTitle": "--","currentPosition": ""
}
编辑:我使用以下代码,我只能读取第一个值:
EDIT: I used the following code that I could read only the first value:
library('rjson')
c <- file.path(Usersfile)
data <- fromJSON(file=c)
推荐答案
令人惊讶的是,此问题从未得到解答!使用jsonlite包,您可以使用paste(x, collapse="")
删除EOF标记将json数据折叠为一个字符元素,以便正确导入R数据帧.我也面临着打印精美的json并出现确切错误:
Surprised this was never answered! Using the jsonlite package, you can collapse your json data into one character element using paste(x, collapse="")
removing EOF markers for proper import into an R dataframe. I, too, faced a pretty-printed json with exact error:
library(jsonlite)
json <- do.call(rbind,
lapply(paste(readLines(Usersfile, warn=FALSE),
collapse=""),
jsonlite::fromJSON))
这篇关于从R中的JSON文件获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!