Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created September 25, 2011 15:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kmizu/1240749 to your computer and use it in GitHub Desktop.
Save kmizu/1240749 to your computer and use it in GitHub Desktop.
A concise JSON DSL in Scala.
import scala.util.DynamicVariable
/**
* A concise JSON DSL in Scala.
* When you want to use, only
* import Jsson._ is needed.
* Note that this program change the semantics of standard -> operator.
* I recommend that you use enclosing block with Jsson as followings:
* {
* import Jsson._
* val obj = %{
* ...
* }
* }
*/
object Jsson {
private val values = new DynamicVariable[Map[String, Any]](null)
class Arrow(receiver: String) {
def ->(value: Any) {
values.value = values.value + ((receiver, value))
}
}
implicit def pimpArrow(arg: String): Arrow = new Arrow(arg)
def %(body: => Any): Map[String, Any] = {
values.withValue(Map[String, Any]()) {
body
values.value
}
}
def $(elements: Any*): List[Any] = {
elements.toList
}
def main(args: Array[String]) {
// Example program
val obj = %{
"x" -> 10
"y" -> 20
"z" -> %{
"a" -> $(1, 2, 3, 4, 5)
"b" -> $(6, 7, %{ "xx" -> "yy" })
}
}
println(obj)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment