Skip to content

Instantly share code, notes, and snippets.

@gluc
Last active August 29, 2015 14:19
Show Gist options
  • Save gluc/05e7c2aef5becd14382b to your computer and use it in GitHub Desktop.
Save gluc/05e7c2aef5becd14382b to your computer and use it in GitHub Desktop.
Converting data.tree to JSON
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)
@gluc
Copy link
Author

gluc commented May 13, 2015

Note that this has now become much easier: https://gist.github.com/gluc/156f6bafc9913b989d14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment