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()
  }
}

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

1 reply
  1. Alex Fruzenshtein
    Alex Fruzenshtein says:

    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”
    }

    Reply

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 *