问题
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
回答1:
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.
回答2:
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")
来源:https://stackoverflow.com/questions/13960900/stepping-into-json-arrays-in-play-framework