How to convert an R data.tree to JSON


Learn how to convert a data.tree Node to a JSON representation, and back, using a custom converter.

PRELIMINARY NOTE: At the time of this post, the ToList method in the data.tree package did not yet exist. As of today, it is much easier to convert a tree to a node. See here for details. However, the method described here can still be useful if you have customization requirements.

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:

 

 

Leave a Reply