rjsonlite

From dataFrame to grouped JSON in R


I have a data frame in R:

ID   var1  var2 
1    12    Name1
1    13    Name4
2    13    Name2
3    14    Name3

and i wish to transform in json grouping the ones that have the same ID:

{
"group":
[
{"ID" : 1, "var1": 12, "var2": "Name1" },
{"ID" : 1, "var1": 13, "var2": "Name4" }
]
},
{
"group":
[
{"ID" : 2, "var1": 13, "var2": "Name2" }
]
},
{
"group":
[
{"ID" : 3, "var1": 14, "var2": "Name3" }
]
}

I also want to save each group on a JSON file, so, for the example above, I will have three JSON files

But I can't figure out a way to do this, neither to mount the JSON as I want nor to save each group separately on a JSON file.


Solution

  • We can use jsonlite

    library(jsonlite)
    library(purrr)
    lst1 <-  map(split(df1, df1$ID), toJSON)
    names(lst1) <- paste0('group', names(lst1))
    toJSON(lst1)