Search code examples
rrjson

how to convert data frame to json format in R


I have a data frame like this:

dput(y)
structure(list(Name = c("Logon", "Logon", "Logon", "Logon", "Logon", 
"Logon", "Logon", "Logon", "Logon", "Logon", "Logon", "Logon", 
"Logon", "Logon", "Logon", "Logon", "Logon", "Logon", "Logon", 
"Logon"), MONTH = structure(c(15002, 15033, 15061, 15092, 15122, 
15153, 15183, 15214, 15245, 15275, 15306, 15336, 15367, 15398, 
15427, 15458, 15488, 15519, 15549, 15580), class = "Date"), TOTAL = c(284697404L, 
268944957L, 297847827L, 287150001L, 277779620L, 262275285L, 284271058L, 
294965702L, 285132804L, 238847338L, 242683830L, 314483537L, 324823553L, 
322896485L, 329044914L, 318228530L, 324395065L, 324988644L, 335464023L, 
336269471L)), .Names = c("Name", "MONTH", "TOTAL"), row.names = c(3755L, 
2875L, 3393L, 13558L, 14278L, 11991L, 12300L, 13040L, 47341L, 
36813L, 44897L, 46836L, 37038L, 46086L, 37261L, 37445L, 48030L, 
37486L, 38074L, 38818L), class = "data.frame")

I need to convert to this data frame to json format like this:

{"name":"Logon","data":[284697404,268944957,... ]}

I have this:

servers <- split(y, y$Name)
dumFun <- function(x){
  sData <- servers[x][[1]]
  if(nrow(sData) >0){
    # create appropriate list
    dumList <- unname(apply(sData[3], 1, function(y) unname(as.list(y))))
    return(toJSON(list(name = x, data = dumList))) 
  }
}

jsData <- lapply(names(servers), dumFun)

This coverts the data as this:

{"name":"Logon","data":[[284697404],[268944957],[297847827],[287150001],[277779620],[262275285],[284271058],[294965702],[285132804],[238847338],[242683830],[314483537],[324823553],[322896485],[329044914],[318228530],[324395065],[324988644],[335464023],[336269471],[324063033],[349017727],[347193478],[355561387],[373885187],[356774443],[386372600],[387573710],[397346365],[388064866],[397269760],[406584525],[353936952]]}"

I need the output to be like this:

{"name":"Logon","data":[284697404,268944957,297847827,287150001],...etc}"

any ideas?


Solution

  • Looks like data should just be a vector rather than a list. Your line here:

    dumList <- unname(apply(sData[3], 1, function(y) unname(as.list(y))))
    

    Is creating a list from the third column of your data. Change it to this:

    dumList <- unname(apply(sData[3], 1, function(y) unname(y)))
    

    Or even simpler and giving the same result:

    dumList <- sData[[3]]
    

    To explain what's happening, look how toJSON converts a simple vector [1, 2, 3] versus a nested list of the same elements.

    x <- 1:3
    toJSON(x)
    # [ 1, 2, 3 ]
    
    x_list <- lapply(x, as.list)
    toJSON(x_list)
    # [ [1], [2], [3] ]
    

    The second case here is what you're seeing. Note, just saw your rjson tag. I'm using the RJSONIO package. I think the results should be same if you're using rjson though.