Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active September 8, 2015 02:14
Show Gist options
  • Save rbobillot/edbe13846af41b805bcf to your computer and use it in GitHub Desktop.
Save rbobillot/edbe13846af41b805bcf to your computer and use it in GitHub Desktop.
Little example of powerful JSON parsing in Scala
import scala.io.Source
import scala.util.parsing.json._
object Main
{
/*
** FLICKR SPECIFIC FUNCTIONS
*/
def getFlickrInfosJson( content:String ) = {
val rawJson = content.split("\n")
.filter( _.contains("modelExport: ") )
.mkString.trim
val cleanJson = rawJson.slice( 13, rawJson.length-1 )
//EQUIVALENT TO: rawJson.drop(13).take(rawJson.length-1)
cleanJson
}
/*
** JSON GETTING FUNCTIONS
*/
def getUrlContent( url:String ) = Source.fromURL( url ).mkString
def jsonOptionToMap( json:Option[Any] ) = json match {
case Some(e) => e.asInstanceOf[ Map[Any,Any] ]
case _ => Map[Any,Any]()
}
/*
** MAIN
*/
def main( av:Array[String] ) = {
val content = getUrlContent( "https://www.flickr.com/photos/batmanta" )
val jsonStr = getFlickrInfosJson( content )
val jsonOpt = JSON.parseFull( jsonStr )
val jsonMap = jsonOptionToMap( jsonOpt )
//show what we got
val mapKeys = jsonMap.keys
val keysStr = mapKeys.mkString( "Keys list: [\t\n\t", ",\n\t", "\n]" )
println( keysStr )
mapKeys.foreach {
e => {
println( "\n\u001b[96m"+ e +"\u001b[0m:" )
println(jsonMap(e))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment