Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalaz Tree to JSON

I'm currently trying to use the Tree class to build a tree-strucuture from a database query. Afterwards I want to convert it to a json object (with playframework api).

Some examples or a bit more documentation for the Tree class would be awesome. I can't get my head arround the draw and drawTree method, which may do a similiar thing.

Example

val tree = ("Root", 100).node(
        ("Category1", 30).leaf,
        ("Category2", 20).node(
          ("Sub1", 15).leaf,
          ("Sub2", 3).leaf,
          ("Sub3", 2).leaf),
        ("Category3", 10).leaf,
        ("Category4", 30).node(
          ("Sub1", 20).leaf,
          ("Sub2", 5).leaf))

This should result in a json tree like this

{
  "name" : "Root",
  "value" : 100,
  "children" : [
     { 
        "name" : "Category1",
        "value": 30
     },
     {
        "name": "Category2",
        "value": 20,
        "children" : [
             {
                "name" : "Sub1",
               "value" : 15"
             } ....
        ]

  ]
like image 879
Muki Avatar asked Nov 23 '13 18:11

Muki


2 Answers

Writing a Writes instance for this tree is quite possible:

import scalaz.Tree, Tree.Node

implicit def treeWrites: Writes[Tree[(String, Int)]] =
  new Writes[Tree[(String, Int)]] {
    def writes(o: Tree[(String, Int)]) = o match {
      case Node((name, value), children) => Json.obj(
        "name" -> name,
        "value" -> value,
        "children" -> JsArray(children.map(Json.toJson(_)))
      )
    }
  }

This is quite a simple implementation and will show an empty children array for the leaves, but that can no doubt be improved with a little extra work.

like image 157
Ben James Avatar answered Nov 15 '22 04:11

Ben James


The drawTree method is just for visualizing a tree, which is something else entirely:

scala> tree.drawTree
res2: String = 
"("Root",100)
|
+- ("Category1",30)
|
+- ("Category2",20)
|  |
|  +- ("Sub1",15)
|  |
|  +- ("Sub2",3)
|  |
|  `- ("Sub3",2)
|
+- ("Category3",10)
|
`- ("Category4",30)
   |
   +- ("Sub1",20)
   |
   `- ("Sub2",5)
"
like image 34
Apocalisp Avatar answered Nov 15 '22 05:11

Apocalisp