數據
我使用的數據是
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...
我剛鍵入它在我的own..so現在..fixed它 – TheLion
你受JSON結構的約束或者你是否靈活? – tospig
我想要的JSON結構,因爲它的核心是寫入掃描該格式 – TheLion