将多行 json 文件转换为 R 数据帧

Convert json file with multiple lines to R dataframe

我正在使用 jsonr 将 JSON 文件读入 R。但是,fromJSON(file="file.json") 命令仅读取文件的第一行。这是 JSON:

{"id":"a","emailAddress":"a@a.com","name":"abc"}
{"id":"b","emailAddress":"b@b.com","name":"def"}
{"id":"c","emailAddress":"c@c.com","name":"ghi"}

如何将所有 3 行都放入 R 数据框中?请注意,以上内容位于单个文件中。

我找到了一个很老套的方法来做到这一点;首先,我用 readr 读取整个 file/string,然后用新行“\n”拆分数据,最后用 fromJSON 解析每一行,然后将其绑定到一个数据帧中:

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))}))