Convert a combination of two data structures to a specific JSON object

57 Views Asked by At

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.

1

There are 1 best solutions below

1
On BEST ANSWER

This seems to work:

df <- data.frame(obj1 = I(obj1), obj2 = I(as.list(obj2)))
toJSON(df)
# [{"obj1":["A"],"obj2":[1]},{"obj1":["B"],"obj2":[1]},{"obj1":["A","B"],"obj2":[1]}]

jsonlite::toJSON(tmp)
# [{"obj1":["A"],"obj2":[1]},{"obj1":["B"],"obj2":[1]},{"obj1":["A","B"],"obj2":[1]}] 

The key points here are

  • Using I() to ensure the column types are list
  • The columns in df need to be named appropriately (obj1 and obj2)
  • obj2 needs to be coerced to list also (as.list(obj2)) in order to get, e.g. "obj2":[1] instead of "obj2":1

I determined this by reverse engineering your desired output:

json <- gsub(
    "'", '"', 
    "[{'obj1':['A'],'obj2':[1]},{'obj1':['B'],'obj2':[1]},{'obj1':['A','B'],'obj2':[1]}]"
)
str(fromJSON(json))
# 'data.frame': 3 obs. of  2 variables:
#  $ obj1:List of 3
#   ..$ : chr "A"
#   ..$ : chr "B"
#   ..$ : chr  "A" "B"
#  $ obj2:List of 3
#   ..$ : int 1
#   ..$ : int 1
#   ..$ : int 1