Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 948
Commander Avatar asked Dec 19 '12 20:12

Commander


1 Answers

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")
like image 199
Julien Lafont Avatar answered Sep 19 '22 05:09

Julien Lafont