Scalaz Tree to JSON
Asked Answered
F

2

5

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"
             } ....
        ]

  ]
Framboise answered 23/11, 2013 at 18:6 Comment(0)
S
8

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.

Sapers answered 23/11, 2013 at 18:30 Comment(0)
M
3

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)
"
Micropathology answered 23/11, 2013 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.