Skip to content

Instantly share code, notes, and snippets.

@kmizu
Created May 22, 2011 07:16
Show Gist options
  • Save kmizu/985246 to your computer and use it in GitHub Desktop.
Save kmizu/985246 to your computer and use it in GitHub Desktop.
JSON like Scala object notation
import scala.util.DynamicVariable
object JssonBuilder {
private val status = new DynamicVariable[Map[String, Any]](null)
class ArrowOperatorExtension(key: String) {
//Warning: this could cause unexpected behavior
def ->(value: Any): (String, Any) = {
val result = (key, value)
status.value = status.value + result
result
}
}
def %(children: => (String, Any)): Map[String, Any] = {
status.withValue(Map[String, Any]()) {
children
status.value
}
}
def $(elements: Any*): List[Any] = elements.toList
implicit def string2ArrowOperatorExtension(key: String)
: ArrowOperatorExtension = {
new ArrowOperatorExtension(key)
}
}
{//prevent to namespace tainted
import JssonBuilder._
val obj = %{
"X" -> 1
"Y" -> 2
"Z" -> 4
"nums" -> $(1, 2, 3, 4, 5,
%{"hoge" -> 1; "foo" -> 2} //nesting is OK
)
}
println(obj)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment