Get array from JSON in Scala Play

You can extract arrays from Json objects in Scala Play if you cast to JsArray, like so:

val speakers = (obj \ "speakerName_ss").toOption match {
  case Some(x: JsValue) => {
    x.asInstanceOf[JsArray].value
  }
  case None => {
    List()
  }
}

One Reply to “Get array from JSON in Scala Play”

  1. Hey Gary,

    Why don’t you use more compact form of array parsing from JSON object?
    Play allows it 🙂

    import play.api.libs.json.Json

    val json = Json.obj(
    “id” -> 1,
    “words” -> List(“apple”, “dog”, “table”)
    )

    val words = (json \ “words”).as[Array[String]]
    words map (word => println(word))

    val optWords = (json \ “words”).asOpt[Array[String]]
    optWords match {
    case Some(words) => words map (word => println(word))
    case None => “Now array found”
    }

Leave a Reply

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