library(rjson)
library(jsonlite)
library(data.table)
library(magrittr)
 
# fake data; 50 rows, 5 item_category_id
set.seed(1234)
d0 <-
  data.table(
    item_id = 1L:50L,
    ttl = runif(50L),
    item_category_id = sample(1L:5L, 50L, replace = T)
  ) %>%
  .[order(item_category_id, item_id, ttl), ]
 
d1 <-
  d0[, .(
    ttl = sum(ttl),
    raw.of.item = list(item_id),
    raw.of.ttl = list(ttl)
  ), by = .(item_category_id)] %>%
  .[order(item_category_id), ]
# apply(d0, 1, list)
 
res <- vector("list", nrow(d1))
for(i in 1:nrow(d1)) {
  res[[i]] <-
    vector("list", 3) %>% set_names(c("item_category_id", "ttl.sum", "items"))
  res[[i]][[1]] <- d1$item_category_id[i]
  res[[i]][[2]] <- d1$ttl[i]
  res[[i]][[3]] <- vector("list", d1$raw.of.item[i][[1]] %>% length)
  for(j in 1:(d1$raw.of.item[i][[1]] %>% length)) {
    res[[i]][[3]][[j]] <- list(`item_id` = d1$raw.of.item[i][[1]][j], `ttl` = d1$raw.of.ttl[i][[1]][j])
  }
}
toJSON(res)
toJSON(res) %>% prettify
