David Z
David Z

Reputation: 7041

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?

Upvotes: 0

Views: 3278

Answers (2)

Valeri Voev
Valeri Voev

Reputation: 2242

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:

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)

Upvotes: 1

J.P. Le Cavalier
J.P. Le Cavalier

Reputation: 1345

You may try the jsonlite package.

library(jsonlite)
 
ls=list(samples=c("a", "b"),
        id=c("sample_id", "sample_id"),
        project="p1",
        date="20220202",
        gender="m")

toJSON(ls)
##  {"samples":["a","b"],"id":["sample_id","sample_id"],"project":["p1"],"date":["20220202"],"gender":["m"]} 

Upvotes: 0

Related Questions