【问题标题】:Getting data from JSON file in R从R中的JSON文件获取数据
【发布时间】:2016-03-01 17:06:02
【问题描述】:

假设我有以下 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)

【问题讨论】:

    标签: json r


    【解决方案1】:

    很惊讶这从来没有得到回答!使用 jsonlite 包,您可以使用 paste(x, collapse="") 删除 EOF 标记以正确导入 R 数据帧,将 json 数据折叠成一个字符元素。我也遇到了一个打印得很漂亮的 json 错误:

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

    【讨论】:

    • 我在数据框中有一列作为 JSON。尝试使用 tidyjson::spread_all() 取消嵌套 json 列。我得到同样的错误 EOF。你知道如何处理它吗?
    • @user5249203 请用可重现的例子提出一个具体问题。上下文很重要。 (完成后,鉴于此答案已超过 5 年,请删除您对未来读者的评论)。
    猜你喜欢
    • 2021-10-25
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多