如何使用data.frame(MyData)创建一个JSON对象,如下所示。我尝试了其他方法,但这个问题看起来很独特。
ID Station Size
1 Zeta Big
2 Zeta Medium
3 Zeta small
4 Yota Big
5 Yota Medium
6 Yota small
预期结果
{
"name": "bubble",
"children": [{
"name": "Zeta",
"children": [{
"name": "big"
}, {
"name": "Medium"
}, {
"name": "small"
}]
}, {
"name": "Yota",
"children": [{
"name": "big"
}, {
"name": "Medium"
}, {
"name": "small"
}]
}]
}
这是我搜索过但无法改变的内容
makeList<-function(x){
if(ncol(x)>2){
listSplit<-split(x[-1],x[1],drop=T)
lapply(names(listSplit),function(y){list(name=y,children=makeList(listSplit[[y]]))})
}else{
lapply(seq(nrow(x[1])),function(y){list(name=x[,-1][y])})
}
}
jsonOut<-toJSON(list(name="MyData",children=makeList(MyData[1])))
cat(jsonOut)
答案 0 :(得分:1)
数据强>
我正在使用的数据是
df <- data.frame(Station = c(rep("Zeta", 3), rep("Yota", 3)),
Size = rep(c("Big","Medium","Small"),2), stringsAsFactors = F)
方式强>
向后工作,我们可以看到我们追求的结构
t <- "{\"name\": \"bubble\",\"children\": [{\"name\": \"Zeta\",\"children\": [{\"name\": \"big\"}, {\"name\": \"Medium\" }, {\"name\": \"small\"}]}, {\"name\": \"Yota\",\"children\": [{\"name\": \"big\"}, {\"name\": \"Medium\"}, {\"name\": \"small\"}]}]}\""
library(jsonlite)
l <- fromJSON(t)
str(l)
#List of 2
#$ name : chr "bubble"
#$ children:'data.frame': 2 obs. of 2 variables:
# ..$ name : chr [1:2] "Zeta" "Yota"
# ..$ children:List of 2
# .. ..$ :'data.frame': 3 obs. of 1 variable:
# .. .. ..$ name: chr [1:3] "big" "Medium" "small"
# .. ..$ :'data.frame': 3 obs. of 1 variable:
# .. .. ..$ name: chr [1:3] "big" "Medium" "small"
要重建这个,我们需要
## first element
lst <- list(name = "bubble")
## second element
l_child1 <- l$children$children[[1]]
l_child2 <- l$children$children[[2]]
l_child <- list(data.frame(name=l_child1), data.frame(name=l_child2))
n <- c("Zeta", "Yota")
df_child <- data.frame(name = n, stringsAsFactors = F)
df_child$children <- l_child
lst <- list(name = "bubble", children = df_child)
toJSON(lst, pretty=F)
# {"name":["bubble"],"children":[{"name":"Zeta","children":[{"name":"big"},{"name":"Medium"},{"name":"small"}]},{"name":"Yota","children":[{"name":"big"},{"name":"Medium"},{"name":"small"}]}]}
所以我们知道我们需要l_child1, l_child2, l_child, df_child
的结构,但是我们如何从原始的df
那里得到那些结果?对于一般情况呢?
<强>解决方案强>
df$Size
向我们提供了l_child
个列表,每个Station
都有一个大小。因此,我们可以使用lapply
向我们提供我们的每个“小组”的儿童名单。
n <- unique(df$Station)
l_child <- lapply(1:length(n), FUN=function(x){
t <- data.frame(name = (df[df$Station == n[x], "Size"]), stringsAsFactors=F)
return(t)
})
我们现在可以构建我们的最终列表
df_child <- data.frame(name = n, stringsAsFactors = FALSE)
df_child$children <- l_child
lst <- list(name = "bubble", children = df_child)
并检查:
> toJSON(lst, pretty=T)
{
"name": ["bubble"],
"children": [
{
"name": "Zeta",
"children": [
{
"name": "Big"
},
{
"name": "Medium"
},
{
"name": "Small"
}
]
},
... etc...