I'm attempting to convert a SQL table into JSON nested format using R. I can import the table into R easily. The problem is now getting all the parent-children relation in the JSON format. I already manage to have some kind of JSON output, but only list all parent individuals with respective children in the following form: ( i will just list the first 6 lines of the table)
[
[
{
"name": ["a"],
"children": ["b"]
},
{
"name": ["b"],
"children": ["c"]
},
{
"name": ["c"],
"children": ["d"]
},
{
"name": ["b"],
"children": ["e"]
},
{
"name": ["e"],
"children": ["f"]
}
]
]
with
library(RJSONIO)
orgTable=orgTable[,c("Manager","ID")]
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],children=x[,2][y])})
}
}
jsonOut = toJSON(list(makeList(orgTable[2:6,])),pretty=TRUE)
cat(jsonOut)
The SQL table is:
Parent Children
a b
b c
c d
b e
e f
What I would like to obtain would be something like:
{
"name": "a",
"children": [
{
"name": "b",
"children": [
{
"name": "c",
"children": [
{
"name": "d"
}
]
},
{
"name": "e",
"children": [
{
"name": "f"
}
]
}
]
}
]
}
Can anyone help? If possible if I could add also info from a third column would be perfect.
The code I present comes from this post but was slightly tweaked for my needs. I'm still quite new at R so please bear with me.
Thanks in advance