atom feed7 messages in com.googlegroups.liftwebJSON builder
FromSent OnAttachments
MariusApr 5, 2008 2:45 am 
MariusApr 5, 2008 5:54 am 
David PollakApr 5, 2008 5:59 am 
MariusApr 5, 2008 6:05 am 
MariusApr 6, 2008 12:02 am 
David PollakApr 6, 2008 3:11 pm 
MariusApr 6, 2008 10:35 pm 
Subject:JSON builder
From:Marius (mari@gmail.com)
Date:Apr 5, 2008 2:45:06 am
List:com.googlegroups.liftweb

Hi,

Hi,

Scala and Lift provide cool support parsing JSON constructs however I haven't seen an implementation of building JSON constructs from Scala code. Do you know any library to do that?

I was actually looking for Scala syntax that would be similar with JSON constructs. I have build some Scala utility that for given JSON construct:

{"name": "Doe", "phone": "1231231231", "title": "Mr.", "other": {"ocupation": "programmer", "age": 29, "enums": [1, 2, 3, 4, 5]}, "arrayofsomething": [{"1": "2", "3": "4"}, "b": "c"]}

Scala correspondent code is:

val json = ("name" -> "Doe") ~ ("phone" -> "1231231231") ~ ("title" -> "Mr.") ~ ("other" -> ("ocupation" -> "programmer") ~ ("age" -> 29) ~ ("enums" -> Array(1, 2, 3, 4, 5))) ~ ("arrayofsomething" -> Array(("1" -> "2") ~ ("3" -> "4"), ("b" -> "c")))

println(stringify(json))

Do you think that this would be beneficial for Lift code?

Here is the Scala code that allows this style of building JSON constructs:

object JSonBuilder { implicit def some2Assoc(t: Any) = new JSonAssoc(t) implicit def list2Assoc(t: List[Any]) = new JSonListAssoc(t)

def stringify(list : List[T] forSome {type T}): String = { def doStringify(list : List[T] forSome {type T}, sep: String): String = { (list map (_ match { case (left, x : List[Any]) => "\"" + left + "\"" + ": {" + doStringify(x, ", ") + "}" case (left, Seq(i @ _*)) => "\"" + left + "\"" + ": [" + (i map ( _ match { case x: List[Any] => "{" + doStringify(x, ", ") + "}" case e : (l, r) => doStringify(List(e), ", ") case e => e }) mkString(", ")) + "]" case (left, right: String) => "\"" + left + "\"" + ": \"" + right + "\"" case (left, right) => "\"" + left + "\"" + ": " + right toString }) mkString(sep)) } "{" + doStringify(list, ",\n") + "}" }

class JSonAssoc(left: T forSome {type T}) { def ~ (right: P forSome {type P}): List[Q] forSome {type Q} = List(left, right) }

class JSonListAssoc(left: List[T] forSome {type T}) { def ~ (right: P forSome {type P}): List[Q] forSome {type Q} = left ::: List(right) }

Br's,