Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export toJSON list of list in R

Tags:

json

list

r

I need to export to json a list of lists to obtain an output JSON like the next one:

{
  "timestamp":"2018-02-01 10:20",
  "aux":[
    {"id":"x1","prog":['A','A','A']},
    {"id":"x2","prog":['A','A','A']},
    {"id":"x3","prog":['A','A','A']}
  ]
}

How can I make a list to get a JSON like that? Thanks in advance.

EDIT:

It's what I'm trying :

l1 <- list(timestamp = "2018-02-01 10:20", 
           aux = list(id = c("x1","x2","x3"), 
           prog = rep('A',3)))

And this is the JSON I get:

{"timestamp":"2018-02-01 10:20",
 "aux":{"id":["x1","x2","x3"],
        "prog":["A","A","A"]}
}
like image 379
manugp4 Avatar asked Oct 16 '22 16:10

manugp4


1 Answers

You can get that structure with an additional level of lists:

l1 <- list(timestamp = "2018-02-01 10:20", 
           aux = list(list(id = "x1", prog = rep('A',3)),
                      list(id = "x2", prog = rep('A',3)),
                      list(id = "x3", prog = rep('A',3))))

jsonlite::toJSON(l1, pretty = TRUE, auto_unbox = TRUE)
#> {
#>   "timestamp": "2018-02-01 10:20",
#>   "aux": [
#>     {
#>       "id": "x1",
#>       "prog": ["A", "A", "A"]
#>     },
#>     {
#>       "id": "x2",
#>       "prog": ["A", "A", "A"]
#>     },
#>     {
#>       "id": "x3",
#>       "prog": ["A", "A", "A"]
#>     }
#>   ]
#> }
like image 70
Ralf Stubner Avatar answered Oct 20 '22 04:10

Ralf Stubner