Search code examples
scalaplayframeworkplay-jsonws

Get filtered JSON value Scala Play


I work with scala play and I use WS to make get a response from an URL.

My JSON example :

[
 {
   "object": "001",
   "object-description": "MODEL",
   "criterion": "TW3",
   "criterion-description": "MODELE X07"
 },
{
  "object": "002",
  "object-description": "TYPE",
  "criterion": "STANDA",
  "criterion-description": "STANDARD TYPE"
}, ...

I want to get only "criterion" field where "object" equal "002". So, in this example the value "STANDA".

A Test:

   ws.url(
    url)
  .get()
  .map { response =>
     Right((response.json \ "object="002"" \\ "criterion").map(_.as[String]))
  }

How I can do that ?

Thanks for your help.


Solution

  • Your can transform the whole response into scala classes using automated formatters and then operate on those.

    case class Data(`object`: String, criterion: String)
    implicit val dataRead = Json.reads[Data]
    
    response.json.as[List[Data]]
      .filter(_.`object` == "002")
      .map(_.criterion)