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 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) {
      } else {

    val files = getListOfFiles("c:\\json")
      (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.

Leave a Reply

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