Moon_Watcher
Moon_Watcher

Reputation: 468

Convert json file with multiple lines to R dataframe

I'm using jsonr to read a JSON file in to R. However, the fromJSON(file="file.json") command is only reading the first line of the file. Here's the JSON:

{"id":"a","emailAddress":"[email protected]","name":"abc"}
{"id":"b","emailAddress":"[email protected]","name":"def"}
{"id":"c","emailAddress":"[email protected]","name":"ghi"}

How do I get all 3 rows into an R dataframe? Note that the above content lives in a single file.

Upvotes: 0

Views: 579

Answers (1)

SebSta
SebSta

Reputation: 496

I found a hacky way to do that; First i read in the whole file/string with readr, then i split the data by new lines "\n", and finally i parse each line with fromJSON and then i bind it into one dataframe:

library(jsonlite)
library(readr)

json_raw   <- readr::read_file("file.json")
json_lines <- unlist(strsplit(json_raw, "\\n"))
json_df    <- do.call(rbind, lapply(json_lines, 
                                  FUN = function(x){as.data.frame(jsonlite::fromJSON(x))}))

Upvotes: 2

Related Questions