Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a list to json in R

Suppose I have a list:

ls=list(samples=c("a", "b"),
     id=c("sample_id", "sample_id"),
     project="p1",
     date="20220202",
     gender="m")
ls
$samples
[1] "a" "b"

$id
[1] "sample_id" "sample_id"

$project
[1] "p1"

$date
[1] "20220202"

$gender
[1] "m"

My question is if there is a good way to save it as a json file such like:

{
  "project": "p1",
  "gender": "m",
  "date": "20220202",
  "samples":
  [
    {"sample_id": "a"},
    {"sample_id": "b"}
  ]
}

Or create the json file via a data.frame?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To get to that exact json representation you would need to adjust your list a bit. Otherwise jsonlite::toJSON should to the job.

To get exactly the json you want, change the list to:

``` r
library(magrittr)
ls=list(samples=list(list(sample_id = "a"), 
                     list(sample_id = "b")),
        project="p1",
        date="20220202",
        gender="m")
ls
#> $samples
#> $samples[[1]]
#> $samples[[1]]$sample_id
#> [1] "a"
#> 
#> 
#> $samples[[2]]
#> $samples[[2]]$sample_id
#> [1] "b"
#> 
#> 
#> 
#> $project
#> [1] "p1"
#> 
#> $date
#> [1] "20220202"
#> 
#> $gender
#> [1] "m"
jsonlite::toJSON(ls, auto_unbox = TRUE) %>% jsonlite::prettify()
#> {
#>     "samples": [
#>         {
#>             "sample_id": "a"
#>         },
#>         {
#>             "sample_id": "b"
#>         }
#>     ],
#>     "project": "p1",
#>     "date": "20220202",
#>     "gender": "m"
#> }
#> 

With your original list:

library(magrittr)
ls=list(samples=c("a", "b"),
        id=c("sample_id", "sample_id"),
        project="p1",
        date="20220202",
        gender="m")
ls
#> $samples
#> [1] "a" "b"
#> 
#> $id
#> [1] "sample_id" "sample_id"
#> 
#> $project
#> [1] "p1"
#> 
#> $date
#> [1] "20220202"
#> 
#> $gender
#> [1] "m"
jsonlite::toJSON(ls) %>% jsonlite::prettify()
#> {
#>     "samples": [
#>         "a",
#>         "b"
#>     ],
#>     "id": [
#>         "sample_id",
#>         "sample_id"
#>     ],
#>     "project": [
#>         "p1"
#>     ],
#>     "date": [
#>         "20220202"
#>     ],
#>     "gender": [
#>         "m"
#>     ]
#> }
#> 

Created on 2022-02-02 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading