Last active
August 29, 2015 14:19
-
-
Save gluc/05e7c2aef5becd14382b to your computer and use it in GitHub Desktop.
Converting data.tree to JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(data.tree) | |
#create an example tree | |
contacts <- Node$new("contacts") | |
contacts$type <- "root" | |
jack <- contacts$AddChild("c1") | |
jack$fullName <- "Jack Miller" | |
jack$isGoodCustomer <- FALSE | |
jack$type <- "customer" | |
jill <- contacts$AddChild("c2") | |
jill$fullName <- "Jill Hampsted" | |
jill$isGoodCustomer <- TRUE | |
jill$type <- "customer" | |
o1 <- jill$AddChild("o1") | |
o1$type <- "order" | |
o1$item <- "Shoes" | |
o1$amount <- 29.95 | |
#This function will convert the Node objects to environments | |
EnvConverter <- function(node) { | |
#We take env and not list, because list has value semantics (just try it with list!) | |
me <- new.env() | |
if (node$type == "customer") { | |
#here you decide which fields you'll want in the JSON | |
#you could also format, transform, etc. | |
me$fullName <- node$fullName | |
me$isGoodCustomer <- node$isGoodCustomer | |
} else if (node$type == "order") { | |
me$item <- node$item | |
me$amount <- node$amount | |
} else { | |
me$name <- node$name | |
} | |
if (!node$isRoot) { | |
node$parent$json[[node$name]] <- me | |
} | |
node$json <- me | |
#dummy return (not needed) | |
return (node$name) | |
} | |
#iterate through the tree and call EnvConverter | |
contacts$Get(EnvConverter) | |
#needed to convert the above created environment to a list | |
ConvertNestedEnvironmentToList <- function(env) { | |
out <- as.list(env) | |
lapply(out, function(x) if (is.environment(x)) ConvertNestedEnvironmentToList(x) else x) | |
} | |
mylist <- ConvertNestedEnvironmentToList(contacts$json) | |
library(rjson) | |
#convert the list to a JSON, using the package of your choice | |
toJSON(mylist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
see http://github.com/gluc/data.tree