how do you convert data frame to a custom json format

Posted by user1471980 on Stack Overflow See other posts from Stack Overflow or by user1471980
Published on 2013-07-02T16:29:28Z Indexed on 2013/07/02 17:05 UTC
Read the original article Hit count: 158

Filed under:
|

I need to convert a data frame to json fomrat in R. My data frame y is this:

dput(y)
structure(list(Name = structure(c(38L, 23L, 16L, 35L, 21L, 6L, 
34L, 15L, 46L, 1L, 43L, 28L, 39L, 27L, 7L, 20L, 14L, 44L, 48L, 
36L), .Label = c("server09", "server10", "server11", "server12", 
"server13", "server14", "server15", "server16", "server17", "server18", 
"server19", "server20", "server21", "server22", "server23", "server24", 
"server25", "server26", "server27", "server28", "server29", "server30", 
"server31", "server32", "server33", "server34", "server35", "server36", 
"server37", "server38", "server39", "server40", "server41", "server42", 
"server43", "server44", "server45", "server46", "server47", "server48", 
"server49", "server50", "server51", "server52", "server53", "server54", 
"server55", "server56", "server57", "server58"), class = "factor"), 
    Date = c(1372737600, 1372737602, 1372737609, 1372737617, 
    1372737618, 1372737618, 1372737643, 1372737646, 1372737648, 
    1372737652, 1372737654, 1372737660, 1372737665, 1372737671, 
    1372737699, 1372737701, 1372737718, 1372737721, 1372737728, 
    1372737731), Cpu = c(3.9025, 36.3042, 2.6075, 3.1338, 0.9474, 
    0.149, 5.4401, 2.5652, 0.3612, 3.2651, 1.8703, 13.8967, 4.2438, 
    5.4401, 2.468, 0.9147, 1.4637, 7.2528, 6.119, 7.7009)), .Names = c("Name", 
"Date", "Cpu"), row.names = c(1L, 42L, 83L, 84L, 125L, 126L, 
127L, 168L, 169L, 202L, 203L, 236L, 277L, 318L, 359L, 360L, 361L, 
362L, 395L, 396L), class = "data.frame")

I need my json file to look like this:

[{
    "name":'server13',
    "data": [ [1372737600,3.9025], [1372737602,10], [1372737609,10] ... [1372737731,20] ]
}, {
    "name":'server14',
    "data": [ [1372737600,4], [1372737602,10], [1372737609,10] ... [1372737731,30] ]
}]

I used rjson package as the following:

p <- toJSON(as.list(y))

I get this output:

"{\"Name\":[\"server13\",\"servar14\",...],\"Date\":[1372737600,1372737602,..],\"Cpu\":[3.9025,36.3042,..]}"

Is there an easy way to do this in R?

© Stack Overflow or respective owner

Related posts about JSON

Related posts about r