Advertisement
Guest User

Untitled

a guest
May 28th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. library(data.tree)
  2.  
  3. #create an example tree
  4. contacts <- Node$new("contacts")
  5. contacts$type <- "root"
  6. jack <- contacts$AddChild("c1")
  7. jack$fullName <- "Jack Miller"
  8. jack$isGoodCustomer <- FALSE
  9. jack$type <- "customer"
  10. jill <- contacts$AddChild("c2")
  11. jill$fullName <- "Jill Hampsted"
  12. jill$isGoodCustomer <- TRUE
  13. jill$type <- "customer"
  14. o1 <- jill$AddChild("o1")
  15. o1$type <- "order"
  16. o1$item <- "Shoes"
  17. o1$amount <- 29.95
  18.  
  19. #This function will convert the Node objects to environments
  20. EnvConverter <- function(node) {
  21. #We take env and not list, because list has value semantics (just try it with list!)
  22. me <- new.env()
  23. if (node$type == "customer") {
  24. #here you decide which fields you'll want in the JSON
  25. #you could also format, transform, etc.
  26. me$fullName <- node$fullName
  27. me$isGoodCustomer <- node$isGoodCustomer
  28. } else if (node$type == "order") {
  29. me$item <- node$item
  30. me$amount <- node$amount
  31. } else {
  32. me$name <- node$name
  33. }
  34.  
  35. if (!node$isRoot) {
  36. node$parent$json[[node$name]] <- me
  37. }
  38. node$json <- me
  39. #dummy return (not needed)
  40. return (node$name)
  41. }
  42.  
  43. #iterate through the tree and call EnvConverter
  44. contacts$Get(EnvConverter)
  45.  
  46. #needed to convert the above created environment to a list
  47. ConvertNestedEnvironmentToList <- function(env) {
  48. out <- as.list(env)
  49. lapply(out, function(x) if (is.environment(x)) ConvertNestedEnvironmentToList(x) else x)
  50. }
  51.  
  52. mylist <- ConvertNestedEnvironmentToList(contacts$json)
  53.  
  54. library(rjson)
  55.  
  56. #convert the list to a JSON, using the package of your choice
  57. toJSON(mylist)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement