Commander
Commander

Reputation: 1322

Stepping into JSON Arrays in Play Framework

I am trying to parse through some json in the play framework from a remote http response. I am trying to get into results[0]->locations[0]->latLng->lat. I am using playframework 2.0 with scala.

Below is the code I am using with a few commented examples of what i've tried so far.

  val promise = WS.url("http://www.mapquestapi.com/geocoding/v2/address?...").get()
  val body = promise.value.get.body
  val json = Json.parse(body)
  val maybeLat = (json \ "results" \ "0" \ "locations" \ "0" \ "latLng" \ "lat").asInstanceOf[String]
  //val maybeLat = (json \ "results[0]" \ "locations[0]" \ "latLng" \ "lat").asInstanceOf[String]
  //val maybeLat = (json \ "results(0) \ "locations(0) \ "latLng" \ "lat").asInstanceOf[String]

  Ok(body).withHeaders(CONTENT_TYPE -> "text/json")

Errors I'm getting from play framework: http://pastebin.com/S5S3nY5D JSON That i'm trying to parse: http://pastebin.com/7rfD0j2n

Upvotes: 6

Views: 5710

Answers (2)

ticofab
ticofab

Reputation: 7717

I think a much better way would be:

val resultsArray = (json \ "results").as[JsArray]
val locations = resultsArray \\ "locations"

at this point, locations will be a list of objects that you can traverse, without having to access them manually through their index.

Upvotes: 6

Julien Lafont
Julien Lafont

Reputation: 7877

Try this, ordinal access must be after the path traversing.

val result = (json \ "results")(0)
val location = (result \ "locations")(0)
val lat = (location \ "latLng" \ "lat")

With this, you can build your one-line solution:

(((json \ "results")(0) \ "locations")(0) \ "latLng" \ "lat")

Upvotes: 8

Related Questions