Assume you have the following data:
obj1 <- list('A', 'B', c('A', 'B'))
obj2 <- rep(1, 3)
The resulting JSON object I need, which is a combination of both, looks like this:
[{'obj1':['A'], 'obj2':[1]},{'obj1':['B'], 'obj2':[1]}, {'obj1':['A','B'], 'obj2':[1]}]
Notice, that even single elements like A are embraced in square brackets!
My question now is, whats the easiest way to generate this JSON structure? obj1 and obj2 do not have to be lists or vectors. It could also be a single dataframe. The important thing is the structure of the final JSON output.
My attempt so far is
tmp <- lapply(obj1, FUN = function(x) {
x <- list("obj1" = x)
x$obj2 <- obj2[1]
obj2 <<- obj2[-1]
return(x)
})
jsonlite::toJSON(tmp)
which does work. It just does not seem to be the best attempt.
This seems to work:
The key points here are
I()to ensure the column types arelistdfneed to be named appropriately (obj1andobj2)obj2needs to be coerced tolistalso (as.list(obj2)) in order to get, e.g."obj2":[1]instead of"obj2":1I determined this by reverse engineering your desired output: