0

我有一个这样的数据框:

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

有任何想法吗?

4

2 回答 2

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

于 2013-10-04T15:04:45.930 回答
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]}"
于 2013-10-04T15:05:35.223 回答