1

In Play 2.3 framework, the response is parsed as JSON. Given the following data:

{"content": [1, 2, 3, 4, 5, 6]}

I tried to access every other elements of the array (i.e. 1, 3, 5) by

// Scala
val array = (response \ "content").as[JsArray].value
for (i <- 0 until array.size / 2)
  println(array(i * 2))

But array(i*2) raised error. What would be the canonical approach of access JsArray via index?

1
  • 1
    You can parse as Array[Int] instead of JsArray. Commented May 9, 2017 at 12:26

1 Answer 1

1

You can try:

for(i <- 0 until array.size if i % 2 == 0)
  println(array(i * 2))

A better way would be to loop over the elements instead:

for((a,i) <- array.zipWithIndex if i % 2 == 0)
  println(a)
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.