2

I have a tibble with JSON column that looks like:

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

I would like to get long format tibble that looks like:

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

There is a huge number of different JSON keys in different rows. Also, ids can have a different number of json keys.
I would like to do it using tidyverse stack.

mihagazvoda
  • 1,057
  • 13
  • 23

1 Answers1

2

One possibility involving dplyr, tidyr, purrr and jsonlite could be:

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]>

The values are stored in a list.

tmfmnk
  • 38,881
  • 4
  • 47
  • 67