Skip to content

Instantly share code, notes, and snippets.

@umitanuki
Created April 27, 2011 18:21
Show Gist options
  • Save umitanuki/944839 to your computer and use it in GitHub Desktop.
Save umitanuki/944839 to your computer and use it in GitHub Desktop.
Tentative JSON pretty printer in Scala
import scala.io._
import scala.util.parsing.json._
object Sca2Main {
def main(args: Array[String]){
val url = "http://search.twitter.com/search.json?q=umitanuki"
val parsed = JSON.parseRaw(Source.fromURL(url).getLines.mkString)
parsed match{
case Some(x:JSONObject) => println("object")
case Some(y:JSONArray) => println("array")
case Some(z:JSONType) => println("jsontype")
case None => println("none")
case _ =>
}
print(pprint(parsed, 0))
}
def pprint(j: Option[Any], l:Int):String = {
val indent = (for(i <- List.range(0, l)) yield " ").mkString
j match{
case Some(o:JSONObject) => {
List("{",
o.obj.keys.map(key => indent + " " + "\"" + key + "\":" + pprint(o.obj.get(key), l + 1)).mkString(",\n"),
indent + "}").mkString("\n")
}
case Some(a:JSONArray) => {
List("[",
a.list.map(v => indent + " " + pprint(Some(v), l + 1)).mkString(",\n"),
indent + "]").mkString("\n")
}
case Some(s: String) => "\"" + s + "\""
case Some(n: Number) => n.toString
case None => "null"
case _ => "undefined"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment