playframework Working with JSON - Scala Scala: Reading a JSON manually


Example

If you are given a JSON string :

val str =
    """{
    |    "name" : "Jsony McJsonface",
    |    "age" : 18,
    |    "hobbies" : [ "Fishing", "Hunting", "Camping" ],
    |    "pet" : {
    |        "name" : "Doggy",
    |        "type" : "dog"
    |    }
    |}""".stripMargin

You can parse it to get a JsValue, representing the JSON tree

val json = Json.parse(str)

And traverse the tree to lookup specific values :

(json \ "name").as[String]          // "Jsony McJsonface"

Useful methods

  • \ to go to a specific key in a JSON object
  • \\ to go to all occurences of a specific key in a JSON object, searching recursively in nested objects
  • .apply(idx) (i.e. (idx)) to go to a index in an array
  • .as[T] to cast to a precise subtype
  • .asOpt[T] to attempt to cast to a precise subtype, returning None if it's the wrong type
  • .validate[T] to attempt to cast a JSON value to a precise subtype, returning a JsSuccess or a JsError
(json \ "name").as[String]          // "Jsony McJsonface"
(json \ "pet" \ "name").as[String]  // "Doggy"
(json \\ "name").map(_.as[String])  // List("Jsony McJsonface", "Doggy")
(json \\ "type")(0).as[String]      // "dog"
(json \ "wrongkey").as[String]      // throws JsResultException
(json \ "age").as[Int]              // 18
(json \ "hobbies").as[Seq[String]]  // List("Fishing", "Hunting", "Camping")
(json \ "hobbies")(2).as[String]    // "Camping"
(json \ "age").asOpt[String]        // None
(json \ "age").validate[String]     // JsError containing some error detail