Created
April 27, 2011 18:21
-
-
Save umitanuki/944839 to your computer and use it in GitHub Desktop.
Tentative JSON pretty printer in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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