How to unbox() a list for appropriate json formatting

60 Views Asked by At

Suppose I have the following list. I would like to remove the outer layer. I tried jsonlite::unbox(), but that function expects either an atomic vector or a 1-row data.frame. purrr::list_flatten() works, but it doesn't give me much control over what is flattened. Is there a better way to do this?

library(dplyr)
library(jsonlite)

people <-
  list(
    list(
      person_1 = 
        list(
          first_name = 'ted',
          last_name = 'johnson',
          age = 45
        ),
      person_2 = 
        list(
          first_name = 'pam',
          last_name = 'wilson'
        )
    )
  )

toJSON(people, pretty = TRUE)
#> [
#>   {
#>     "person_1": {
#>       "first_name": ["ted"],
#>       "last_name": ["johnson"],
#>       "age": [45]
#>     },
#>     "person_2": {
#>       "first_name": ["pam"],
#>       "last_name": ["wilson"]
#>     }
#>   }
#> ]

unbox(people)
#> Error: Only atomic vectors of length 1 or data frames with 1 row can be unboxed.

My expected output is

#>   {
#>     "person_1": {
#>       "first_name": ["ted"],
#>       "last_name": ["johnson"],
#>       "age": [45]
#>     },
#>     "person_2": {
#>       "first_name": ["pam"],
#>       "last_name": ["wilson"]
#>     }
#>   }
0

There are 0 best solutions below