Search code examples
jsonscalaviewplayframework-2.3jsobject

Play 2.3.x Scala - How to display json data on view?


I am coming from the Node world and I am having trouble wrapping my head passing json to the view and then displaying data.

I am hitting an api to fetch 2 profiles. The res.body is json. The response is fairly large - but now I only want to display some data in my view.

      // Application.scala
      val profile1 = WS.url(player1URL).get()     
      val profile2 = WS.url(player2URL).get()

      Future.sequence(Seq(profile1, profile2)).map { 
          response => Ok(views.html.index.render(
              Json.obj("player1" -> response(0).json, "player2" -> response(1).json)))
      }


    //index.scala.html
    @(z: play.api.libs.json.JsObject)

    <body>
      @z.player1  //value player1 is not a member of play.api.libs.json.JsObject
      // ideally I want
      // z.player1.battleTag //displays battle tag
      // z.player1.paragonLevel //displays paragon level
   </body>

I can display my json as string or even as json. But I cannot access the values by keys. I just want to display 3 or 4 items from each player as html. Then I can clean it up with some css later.


Solution

  • You can access you json by using code similar to this:

    @{(z\"player1"\"battleTag").as[String]}
    

    Or even:

    <script>
        var jsono =  @Html(z.toString) ;
        alert(jsono.player1.battleTag)
    </script>