PlayJson Max n for which apply(n) is Defined

Dear all,

How do I know the max n for which apply(n) is defined for a JsValue? I need that because I’d like to iterate over a JSON array from 0 to n. Right now, the way I do so is:

    var myjson = ...

    while(myjson.head.isDefined) {
      val head = myjson.head.get
      /* ... process head ... */
      myjson = myjson.tail.get
    }

which is both very nasty and inefficient. Any better way?

TIA,
–Hossein

myjson.last.get should work. However, it maybe just as inefficient but nicer for the eyes.

Not really. That just returns the last element in the array. It will facilitate backward iteration over the array. But, such an iteration will again involve truncation and overwriting of myjson. Doesn’t help a for loop for example:

val n = ... //number of elements in myjson as an array
for(i <- 0 to n) {/* ... process myjson(i).get ... */}

The question is how do I get the first line above done?

Just match?

def processArray(vs: Seq[JsValue]) = ???

myjson match {
  case JsArray(vs) => processArray(vs)
  case v => ???
}

That does. Thanks! :slight_smile: