2

I have a list of lists, each of them with format like the following:

list( name = 'foo',
       type = 'bar',
       attributes= list(
         list(name='color', value='blue'  ),
         list(name='batch', value=123),
         list(name='is_available', value='true')  )
       )

i.e. with pairs of names and values of attributes. How I can transform this into this format

list( name = 'foo',
       type = 'bar',
       attributes= list(
         color='blue' ,
         batch=123,
         is_available=TRUE )
)

Preferably in a tidyverse way.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
Yuriy Barvinchenko
  • 1,465
  • 1
  • 12
  • 17
  • Not quite what you asked for, but `fromJSON(toJSON(x$attributes))` using `library(jsonlite)` may be worth looking at. – Ian Gow May 27 '23 at 13:57

2 Answers2

5

Here is a one-liner base R way. The only difference from the expected output is in the attribute is_available, see at end.

lst <- list( name = 'foo',
             type = 'bar',
             attributes= list(
               list(name='color', value='blue'  ),
               list(name='batch', value=123),
               list(name='is_available', value = 'true')  )
)
out <- list( name = 'foo',
             type = 'bar',
             attributes= list(
               color='blue' ,
               batch=123,
               is_available = TRUE )
             )

lst$attributes <- sapply(lst$attributes, \(x) setNames(x[2], x[1]))

lst$attributes$is_available
#> [1] "true"
out$attributes$is_available
#> [1] TRUE

Created on 2023-05-27 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
2

Perhaps something like this:

library(dplyr)
library(purrr)

list_ <- list( name = 'foo',
      type = 'bar',
      attributes= list(
        list(name='color', value='blue'  ),
        list(name='batch', value=123),
        list(name='is_available', value='true')  )
)

list_ %>% 
  modify_in("attributes", \(x) {
    transposed <- list_transpose(x)
    set_names(transposed$value, transposed$name) %>% 
      modify_in("is_available", readr::parse_logical)
    }) %>% glimpse()
#> List of 3
#>  $ name      : chr "foo"
#>  $ type      : chr "bar"
#>  $ attributes:List of 3
#>   ..$ color       : chr "blue"
#>   ..$ batch       : num 123
#>   ..$ is_available: logi TRUE

Created on 2023-05-27 with reprex v2.0.2

margusl
  • 7,804
  • 2
  • 16
  • 20