【发布时间】:2019-07-10 17:10:23
【问题描述】:
我正在努力解析 R 中的 JSON,它在字符串中和键/值对(和整个对象)之间都包含换行符。
我的意思是这种格式:
{
"id": 123456,
"name": "Try to parse this",
"description": "Thought reading a JSON was easy? \r\n Try parsing a newline within a string."
}
{
"id": 987654,
"name": "Have another go",
"description": "Another two line description... \r\n With 2 lines."
}
假设我将此 JSON 保存为 example.json。我尝试了各种技术来克服解析问题,在 SO 的其他地方建议。以下均无效:
library(jsonlite)
foo <- readLines("example.json")
foo <- paste(readLines("example.json"), collapse = "")
bar <- fromJSON(foo)
bar <- jsonlite::stream_in(textConnection(foo))
bar <- purrr::map(foo, jsonlite::fromJSON)
bar <- ndjson::stream_in(textConnection(foo))
bar <- read_json(textConnection(foo), format = "jsonl")
我认为这确实是 NDJSON 格式,但没有一个专门的软件包可以处理它。有人建议streaming in the data with either jsonlite or ndjson(or this one 和this one)。其他人建议mapping the function across lines (or similarly in base R)。
一切都会引发以下错误之一:
Error: parse error: trailing garbage 或 Error: parse error: premature EOF 或打开文本连接时出现问题。
有人有解决办法吗?
【问题讨论】:
-
那个块(作为一个整体)是不合法的json,这两个字典通常是(a)在一个列表中,还是(b)逐行存储行,ndjson 风格?
-
:
jsonlite::prettify( )是否适合您? -
嗨@r2evans,不,这是我必须使用的 - 我看不出有什么方法可以将它强制转换回这两种格式中的任何一种......
-
谢谢@Dave2e - 我刚刚尝试
minify作为第一步,但它以与我其他尝试阅读它的方式类似的方式失败......
标签: r json parsing newline ndjson