[英]parse hierarchical json into table in R
我有很多 json arrays 不遵循我习惯的“属性”:“值”格式。 我想一一阅读并将它们解析成表格。 然后我想合并表格。 我被解析位卡住了。
所有 arrays 都是来自论坛的标记帖子并具有以下结构:
myjson = '
[{
"posts": [
[9999991, "Here is some text."],
[9999992, "Here is some other, unrelated text."]
],
"id": "123456",
"label": "whatever"
}]
'
其中一个数组有一个“posts”、一个“id”和一个“label”,没有别的,但是“posts”下的 []-s 的数量是任意的(这里是 2)。
当我使用jsonlite
将其解析为 R 时,我得到了一团糟。 当我使用RJSONIO
或rjson
时,我会得到列表列表的列表。
通过将列表中的信息拼凑在一起,我可以达到所需的 output ,但这很可怕且容易出错:
myj = rjson::fromJSON(myjson)
post_id = c(
myj[[1]]$posts[[1]][[1]],
myj[[1]]$posts[[2]][[1]]
)
post_content = c(
myj[[1]]$posts[[1]][[2]],
myj[[1]]$posts[[2]][[2]]
)
dplyr::tibble(
id = myj[[1]]$id,
label = myj[[1]]$label,
post_id = post_id,
post_content = post_content
)
> # A tibble: 2 x 4
> id label post_id post_content
> <chr> <chr> <dbl> <chr>
> 1 123456 whatever 9999991 Here is some text.
> 2 123456 whatever 9999992 Here is some other, unrelated text.
这不适合迭代(我不知道如何引用myj[[1]]$posts[[1...i]][[1...ii]]
)并且可能非常慢。
一定有更好的办法!
尝试使用jsonlite::fromJSON
unnest
数据并取消嵌套值。
library(dplyr)
jsonlite::fromJSON(myjson) -> tmp
tmp %>%
mutate(posts = purrr::map(posts, data.frame)) %>%
tidyr::unnest(posts)
# X1 X2 id label
# <chr> <chr> <chr> <chr>
#1 9999991 Here is some text. 123456 whatever
#2 9999992 Here is some other, unrelated text. 123456 whatever
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.