How to write to json with children from R

前端 未结 3 587
日久生厌
日久生厌 2020-11-29 23:27

I want to turn an R data.frame into a JSON object in order to use it for preparing data visualizations with d3.js. I found a lot of questions that asked how to get JSON into

3条回答
  •  Happy的楠姐
    2020-11-29 23:53

    This is a recursive approach which is cleaner:

    require(RJSONIO)
    
    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],Percentage=x[,2][y])})
      }
    }
    
    
    jsonOut<-toJSON(list(name="MyData",children=makeList(MyData[-1])))
    cat(jsonOut)
    

提交回复
热议问题