Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from JSON file in R

Tags:

json

r

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)
like image 741
Mpizos Dimitris Avatar asked Nov 27 '15 13:11

Mpizos Dimitris


People also ask

Which function is used to read a JSON file in R?

Reading the JSON file in R is a very easy and effective process. R provide from JSON() function to extract data from a JSON file. This function, by default, extracts the data in the form of a list. This function takes the JSON file and returns the records which are contained in it.

How do I read a JSON file into a DataFrame?

Reading JSON Files using Pandas To read the files, we use read_json() function and through it, we pass the path to the JSON file we want to read. Once we do that, it returns a “DataFrame”( A table of rows and columns) that stores data.


1 Answers

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))
like image 173
Parfait Avatar answered Sep 25 '22 00:09

Parfait