Scala Play JSON example

The following example shows how to use the JSON APIs in Scala play to parse JSON files. Note that you have to use special operators to get at the data. If your schema isn’t well-defined, you’ll want to get Options out of Play, and then use Scala pattern matching on the output.

import java.io.File
import org.apache.commons.io.FileUtils
import play.api.libs.json._
 
object Speaker {
  def main(args: Array[String]): Unit = {
    def getListOfFiles(dir: String): List[File] = {
      val d = new File(dir)
      if (d.exists && d.isDirectory) {
        d.listFiles.filter(_.isFile).toList
      } else {
        List[File]()
      }
    }
 
    val files = getListOfFiles("c:\\json")
 
    files.map(
      (file) => {
        val json = FileUtils.readFileToString(file, "utf-8")
        val obj = Json.parse(json)
 
        (obj \ "title_s").asOpt[String] match {
          case Some(data: String) => println(data)
          case None => println("No title")
        }
      }
    )
  }
}

Play provides a stringify function (Json.stringify) but unlike Javascript, you can’t control the format. You can use “Json.prettyPrint” instead, which still doesn’t let you control the output, but it does use the one true path of two space tabs.

If you want a good book on Scala, take a look at Programming Scala (I'm currently reading through this).

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *