如何在R中将数据帧转换为json格式

时间:2013-10-04 14:36:11

标签: r rjson

我有一个这样的数据框:

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")

我需要将此数据框转换为json格式,如下所示:

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

我有这个:

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)

这会将数据转换为:

{"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]]}"

我需要输出如下:

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

任何想法?

2 个答案:

答案 0 :(得分:1)

看起来data应该只是一个向量而不是列表。你的话在这里:

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

从数据的第三列创建列表。将其更改为:

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

甚至更简单并给出相同的结果:

dumList <- sData[[3]]

要解释发生了什么,请查看toJSON如何转换简单的向量[1,2,3]与相同元素的嵌套列表。

x <- 1:3
toJSON(x)
# [ 1, 2, 3 ]

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

这里的第二个案例是你所看到的。请注意,只看到了rjson标记。我正在使用RJSONIO包。我认为如果您使用rjson,结果应该相同。

答案 1 :(得分:1)

你的toJSON列表有点偏。它需要命名的矢量列表。

重要的:
组合列表时,

使用它:c( list1, list2)
   不是这样的:list(list1, list2)

后者将创建额外的嵌套级别,这不是您想要的。

以下是获取JSON字符串的快速方法:

# for syntax ease
library(data.table)


as.data.table(y)[
    # the outer `list` is for data.table, the inner `lists` are for `JSON`
  , list(JSON = toJSON(c(list(name=Name), list(data=TOTAL)))), by=Name][, JSON]

[1] "{\"name\":\"Logon\",\"data\":[284697404,268944957,297847827,287150001,277779620,262275285,284271058,294965702,285132804,238847338,242683830,314483537,324823553,322896485,329044914,318228530,324395065,324988644,335464023,336269471]}"