读取 jsonl(json 行)文件

Eri*_*ole 3 r jsonlite jsonlines

使用以下命令可以读取 json 文件:

library(jsonlite)
json_text <- readLines("tect.json", warn = FALSE, encoding = "UTF-8")
Run Code Online (Sandbox Code Playgroud)

解析 JSON 数据

json_data <- fromJSON(txt = paste(json_text, collapse = ""))
Run Code Online (Sandbox Code Playgroud)

tect.json 文件中的数据格式如下:

[
  {
    "id": 1,
    "name": "Apple",
    "color": "red",
    "price": 0.99
  },
  {
    "id": 2,
    "name": "Banana",
    "color": "yellow",
    "price": 0.5
  },
  {
    "id": 3,
    "name": "Orange",
    "color": "orange",
    "price": 0.75
  }
]
Run Code Online (Sandbox Code Playgroud)

但是,如果 tech.json 具有这种格式,如何将其作为 json 文件读取并将其转换为数据帧?

{"id": 1, "name": "Apple", "color": "red", "price": 0.99 }
{"id": 2, "name": "Banana", "color": "yellow", "price": 0.5 }
{"id": 3, "name": "Orange", "color": "orange", "price": 0.75 }
Run Code Online (Sandbox Code Playgroud)

如果我尝试开始时的选项来读取此文件,我会收到如下错误:

Error: parse error: trailing garbage
          nge":"
Run Code Online (Sandbox Code Playgroud)

怎么可能读取这个文件呢?

Sam*_*amR 5

您的第二个示例不是有效的 json。它是jsonl

JSONL 是一种基于文本的格式,使用 .jsonl 文件扩展名,本质上与 JSON 格式相同,只是使用换行符来分隔 JSON 数据。它也被称为 JSON Lines。

要处理这样的文件,您可以将每一行读取为 json,然后读取rbind()结果。_ 基本 R 方法(占位符至少需要 R 4.2 ):

library(jsonlite)
json_text <- readLines("tech.json", warn = FALSE, encoding = "UTF-8")

lapply(json_text, fromJSON) |>
    do.call(rbind, args = _) |>
    data.frame()

#   id   name  color price
# 1  1  Apple    red  0.99
# 2  2 Banana yellow   0.5
# 3  3 Orange orange  0.75
Run Code Online (Sandbox Code Playgroud)

或者,这是一种dplyr方法:

library(dplyr)
lapply(json_text, fromJSON) |>
    bind_rows()

# # A tibble: 3 x 4
#      id name   color  price
#   <int> <chr>  <chr>  <dbl>
# 1     1 Apple  red     0.99
# 2     2 Banana yellow  0.5 
# 3     3 Orange orange  0.75
Run Code Online (Sandbox Code Playgroud)

为了完整起见,这里是data.table执行相同操作的方法:

library(data.table)
lapply(json_text, fromJSON) |>
    rbindlist()
#       id   name  color price
#    <int> <char> <char> <num>
# 1:     1  Apple    red  0.99
# 2:     2 Banana yellow  0.50
# 3:     3 Orange orange  0.75
Run Code Online (Sandbox Code Playgroud)