jsmap - simple json transformations Subscribe Pub Share

I just touched on a simple utility I had created, to play with json documents (and similar tree structures) via Map and List, see jsmap - simplified json.

This utility can also do very simple structure transformations jt like:

      import razie.js._

      jt(root) {
        // prune empty lists
        case (_, "children", x: List[_]) if (x.isEmpty) => ("" -> x)
      }
 

It removes the properties called "children" if they are an empty list, anywhere they appear (path is _) and it also stops the original transformation from recursing into that node.

      import razie.js._

      jt(tojmap) {
        case ("/", "xurl", u) => ("data" -> Map(
          "$dim" -> "10",
          "url" -> u))
        case (path, "links", l: List[_]) => ("adjacencies" -> jt(l, path) {
          case (_, "to", t) => ("nodeTo", t)
          case (_, "type", t) => ("data" -> Map("weight" -> "1"))
        })
      }

This will do several transformations, as you see some are path dependent (case ("/"... matches the root node only). Note that if you want to recurse in the original tree, you do it yourself by invoking the jt again.

If there was a property "type" of a list of objects "links", it will be transformed into an object "data" with weight etc.

You can see this very simple transformation can be tremendously flexible. I found it easy to use...

So for instance, to change the name of the "depth" property of every third level object to "goodDepth" it would be something like:

      import razie.js._

      tojsons(jt(parse(jsonString)) {
        case (path, "depth", value) if path.split("/").size == 3 => ("goodDepth" -> "good")
        }
      })

Why use other libraries that encode transformations into JSON or XML or any other language, when you have the full power of scala and instant testing, debugging, content assist etc?


Was this useful?    

By: Razie | 2015-06-04 .. 2016-05-16 | Tags: post , scala , programming


See more in: Cool Scala Subscribe

Viewed 1362 times ( | History | Print ) this page.

You need to log in to post a comment!