如何将df转换为json文件,数字为数字

时间:2014-03-21 20:40:57

标签: r

我正在尝试将数据帧转换为json格式。这是我的数据框,名为x:

structure(list(Desc = c("Web", "Mobile", "TV", "Store"), Total = c(223786915, 
42053151, 232299534, 26317530), Name = c("Total Login", "Total Login", 
"Total Login", "Total Login")), .Names = c("Desc", "Total", "Name"
), row.names = c(NA, 4L), class = "data.frame")

这是功能:

servers <- split(x,x$Name)
dumFun <- function(x){
  sData <- servers[x][[1]]
  if(nrow(sData) >0){
    # create appropriate list
    dumList <- unname(apply(sData[,c(1,as.numeric(2))], 1, function(y) unname(as.list(y))))
    return(toJSON(list(name = x, data = dumList))) 
  }
}
jsData <- lapply(names(servers), dumFun)
jsInd <- sapply(jsData, is.null)
p<-paste(jsData[!jsInd], collapse = ',')
p<-paste('[', p, ']')

将x $ Total视为字符串。我需要x $ Total为数字,并且周围没有双引号。我有什么想法可能做错了吗?

1 个答案:

答案 0 :(得分:2)

jsonlite能做你想做的吗?

例如,您可以执行jsonlite::toJSON(x)

res <- jsonlite::toJSON(x, pretty=TRUE)
cat(res)

[
{
    "Desc" : "Web",
    "Total" : 223786915,
    "Name" : "Total Login"
},
{
    "Desc" : "Mobile",
    "Total" : 42053151,
    "Name" : "Total Login"
},
{
    "Desc" : "TV",
    "Total" : 232299534,
    "Name" : "Total Login"
},
{
    "Desc" : "Store",
    "Total" : 26317530,
    "Name" : "Total Login"
}
]