0

I´m using Scala.js and want to read a JSON i get from my backend.
My problem is, i don't know how to work with my response as json. All examples i found use JSON.toJson(xhr.responseText) but this only works if i get one String (right?)
Also i dont want to parse the JSON in Objects (in this example Users) I use the Json lib from the Play-Framework.
Example for Json:

[
    {
        "name": "User1",
        "age": 18
    },
    {
        "name": "User2",
        "age": 18
    },
    {
        "name": "User3",
        "age": 18
    }
]

My Code

 val xhr = new dom.XMLHttpRequest()
    xhr.open("GET", backend + "/ROUTE")
    xhr.responseType="json"
    xhr.onload = { (e: dom.Event) =>
       println(xhr.response) 
       //What i want
       // for (user<-response) println(user("age"),user("name")) 
    }
    xhr.send()

The output is

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I tried things like

val js=Json.obj("users"->xhr.response)

and so on.

I guess i have a misunderstanding how exactly

 xhr.responseType="json"

works but can't figure it out.

I know how i would do it in "normal" Play json("name")

1 Answer 1

1

When you are using responseType = "json" you instruct the Browser to interpret the response as a normal Javascript Object.

In scalasjs terms, this would be a value of type js.Object too (see https://www.scala-js.org/doc/interoperability/types.html).

More specifically, when you are receiving a JSON Array, you could expect a js.Array[T] in scalajs:

import scala.scalajs.js

...

req.onload = { e: dom.Event =>
  if (js.Array.isArray(req.response)) {
    val array =  req.response.asInstanceOf[js.Array[js.Dynamic]]

    for (user <- array) {
      println(user.name)
    }
  }
}

Instead of using responseType = "json", you might consider doing it like this:

req.onload = { e: dom.Event =>
  val r = js.JSON.parse(req.responseText)

  r match {
    case jsonlist: js.Array[js.Dynamic] =>
      for (user <- jsonlist) {
        println(user)
       }
    }
  }
}

However, if you want to use play-json, you would not want to set responseType = "json" at all, just transfer it as a String and call Json.parse on it:

val json = Json.parse(req.responseText)

println((json \ 1 \ "name").as[String])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.