5

Lets say that I have the following json file:

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

I use the following code:

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

and I have the following error:

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

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?

Also this one doesnt work:

{ "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)
Mpizos Dimitris
  • 4,819
  • 12
  • 58
  • 100

1 Answers1

14

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))
Parfait
  • 104,375
  • 17
  • 94
  • 125
  • I have a one column as JSON, in a data frame. Trying to unnest json column using tidyjson::spread_all(). I get the same error EOF., Do you know how to approach it ? – user5249203 Jul 22 '21 at 20:56
  • 1
    @user5249203 Please ask a specific question with reproducible example. Context matters. (Once done, please remove your comment for future readers given this answer is over 5 years old). – Parfait Jul 23 '21 at 00:03