Scala Play handling JSON objects and arrays

D. Park Source

I am making a third party API call using Play WS to get back a JSON object with a list of objects. I want to iterate through this list and add a key/value to each item. I am new to Scala and typed languages, and it is really difficult to deal with JSON in Scala. Any help would be greatly appreciated. Thanks!

This is what I have right now:

def getAll(filters: String) = Action.async { request =>
  val api_url = API_URL + "search?api_key=" + API_KEY + filters

  ws.url(api_url).get().map { response =>
    val body = response.body
    val json = Json.parse(body)
    val listings = (json \ "listings").get

  // I want to iterate through listings, which is of type JsValue
  // And for each object, I want to add a key/value pair



answered 5 days ago Pitagoras #1

Once you have a JsonNode you have to cast it to ObjectNode to be able to add a property. For example, having listings: EDIT:

 listings.asInstanceOf[JsArray]{ jsvalue =>
  (jsvalue.asInstanceOf[JsObject]) + ("extra" -> JsString("something"))

comments powered by Disqus