Site icon R-bloggers

How to convert an R data.tree to JSON

[This article was first published on ipub » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I have recently published the data.tree R package to CRAN. It provides OO-style tree building, with standard tree traversal methods. Read the vignette about data.tree features if you are interested, or the one explaining how to use data.tree for classification models.

I’ve been asked how to convert a data.tree to an XML or JSON. So here’s the answer.

Bear in mind that data.tree has not been built for this purpose, so we need to do a few extra steps and the code is not really beautiful. However, thinking of it, it’s a natural application, as JSON and XML documents are inherently trees. Also, I’m surprised how easy it was to come up with a generic answer. So here it is:

 

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)

 

The post How to convert an R data.tree to JSON appeared first on ipub.

To leave a comment for the author, please follow the link and comment on their blog: ipub » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.