r - 将多行的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 数据框中?请注意,上述内容位于单个文件中。
解决方案
我找到了一个 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))}))
推荐阅读
- laravel - Laravel 查询比当前时间更近的日期
- html - Bootstrap 4 行与其父级重叠
- ios - 通用链接:如何以编程方式返回?
- node.js - Firestore 安全规则中的复杂功能
- html - 我怎样才能在我的桌子内滚动?
- unix - 将环境变量添加到 MobaXterm 的最佳方法
- javascript - 为什么要引用 this 变量来修改 DOM 元素?:澄清 Vue 组件中的“this”
- python - python selenium:“geckodriver”可执行文件需要在路径中添加可执行文件到路径后
- java - 如何将单独的进程执行的 Junit 测试转换为在 Idea 中以标准方式显示
- c++ - 检查数组的相邻值