从 tibble json 列中提取 key-value 对并将它们取消嵌套到不同的行中

Extract key-value pairs from tibble json column and unnest them into different rows

我有一个 JSON 列的标题,看起来像:

df <- tibble(
  id = c(1, 2), 
  json_col = c('{"a": [1,2,3], "b": [4, 5, 6]}', '{"f": [100,2,8]}')
)

我想要长格式的 tibble,如下所示:

id | key | val
----------------
1 | "a" | c(1,2,3)
1 | "b" | c(4,5,6)
2 | "f" | c(100,2,8)

不同的行中有大量不同的 JSON 键。此外,id 可以有不同数量的 json 键。
我想使用 tidyverse 堆栈来完成。

涉及 dplyrtidyrpurrrjsonlite 的一种可能性是:

df %>%
 mutate(json_col = map(json_col, ~ fromJSON(.) %>% as.data.frame())) %>%
 unnest(json_col) %>%
 pivot_longer(-id, values_drop_na = TRUE) %>%
 group_by(id, name) %>%
 summarise(value = list(value)) 

    id name  value    
  <dbl> <chr> <list>   
1     1 a     <int [3]>
2     1 b     <int [3]>
3     2 f     <int [3]>

值存储在列表中。