将分层json解析为R中的表

  • 本文关键字:分层 json r json dplyr
  • 更新时间 :
  • 英文 :


我有很多json数组不遵循"属性":"值";格式我习惯了。我想一个接一个地阅读它们,并将它们解析成表。然后我想把桌子组合起来。我被解析部分卡住了。

所有数组都是来自论坛的标记帖子,并具有以下结构:

myjson = '
[{
"posts": [
[9999991, "Here is some text."],
[9999992, "Here is some other, unrelated text."]
],
"id": "123456",
"label": "whatever"
}]
'

在一个阵列具有一个"0"的情况下;帖子";,一个";id";,以及一个";标签";除此之外什么都没有,只是";帖子";是任意的(这里是2(。

当我使用jsonlite将其解析为R时,我得到了一个混乱的混乱。当我使用RJSONIOrjson时,我会得到列表的列表。

我可以通过将列表中的信息拼凑在一起来获得所需的输出,但这很可怕,而且容易出错:


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::fromJSONunnest的值读取数据。

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

最新更新