首页 > 解决方案 > 将多行的json文件转换为R数据框

问题描述

我正在使用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 数据框中?请注意,上述内容位于单个文件中。

标签: rjsondataframerjson

解决方案


我找到了一个 hacky 方法来做到这一点;首先我用readr读入整个文件/字符串,然后我用新行“\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))}))

推荐阅读