Search code examples
jsonrrjson

I need to convert data frame into json format in R


I have this data frame:

dput(head(dat))

structure(list(out = c(5, 0, 0, 0, 0, 0), Date = c(1423825200000, 
1423825500000, 1423825800000, 1423826100000, 1423826400000, 1423826700000
)), .Names = c("out", "Date"), row.names = c(NA, 6L), class = "data.frame")

I need to convert this to json format.

I tried this:

dList <- unname(apply(dat[,1:2], 1, function(y) unname(as.list(y))))
df1<-toJSON(list( data = dList))

I get something like this:

{"data":[[[5],[1423825200000]],[[0],[1423825500000]],[[0],[1423825800000]],[[0],[1423826100000]],[[0],[1423826400000]],[[0],[1423826700000]],[[0],[1.423827e+12]],[[0],[1423827300000]],[[0],[1423827600000]],[[0],[1423827900000]]}

I need this to be :

 [[5, 1423825200000.0], [0, 1423825500000.0], [0, 1423825800000.0], [0, 1423826100000.0], [0, 1423826400000.0], [0, 1423826700000.0], [0, 1423827000000.0], [0, 1423827300000.0], [0, 1423827600000.0], [0, 1423827900000.0]]

Any ideas how I could this in R


Solution

  • Convert dat to a matrix, then run it through jsonlite::toJSON

    jsonlite::toJSON(as.matrix(dat))
    # [[5,1423825200000],[0,1423825500000],[0,1423825800000],[0,1423826100000],[0,1423826400000],[0,1423826700000]]