[英]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.