How to write to json with children from R

前端 未结 3 603
日久生厌
日久生厌 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条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 23:53

    Using a combination of split and subset may get what you want. For example

    library(RJSONIO)
    list1<-split(subset(MyData,select=c(-Location)),Mydata$Location)
    list2<-lapply(list1,function(x){split(subset(x,select=c(-Station)),x$Station,drop=TRUE)})
    list3<-lapply(list2,function(x){lapply(x,function(y){split(subset(y,select=c(-Size,-ID)),y$Size,drop=TRUE)})})
    jsonOut<-toJSON(list(MyData=list3))
    jsonOut1<-gsub('([^\n]*?): \\{\n "Percentage"','\\{"name":\\1,"Percentage"',jsonOut)
    jsonOut2<-gsub('"([^"]*?)": \\{','"name":"\\1","children":\\{',jsonOut1)
    
    cat(jsonOut2)
    {
     "name":"MyData","children":{
     "name":"Alpha","children":{
     "name":"Yota","children":{
    {"name": "Big","Percentage":   0.85 
    },
    {"name":"Medium","Percentage":   0.19 
    },
    {"name":"small","Percentage":   0.89 
    } 
    },
    "name":"Zeta","children":{
    {"name": "Big","Percentage":   0.63 
    },
    {"name":"Medium","Percentage":   0.43 
    },
    {"name":"small","Percentage":   0.47 
    } 
    } 
    },
    "name":"Beta","children":{
     "name":"Meta","children":{
    {"name": "Big","Percentage":   0.89 
    },
    {"name":"Medium","Percentage":   0.71 
    },
    {"name":"small","Percentage":   0.59 
    } 
    },
    "name":"Theta","children":{
    {"name": "Big","Percentage":   0.09 
    },
    {"name":"Medium","Percentage":   0.33 
    },
    {"name":"small","Percentage":   0.79 
    } 
    } 
    } 
    } 
    }
    

提交回复
热议问题