tags:

views:

96

answers:

3

I would like to traverse a collection resulting from the Scala JSON toolkit at github. The problem is that the JsonParser returns "Any" so I am wondering how I can avoid the following error:

"Value foreach is not a member of Any".

val json = Json.parse(urls)

for(l <- json) {...}

object Json {
  def parse(s: String): Any = (new JsonParser).parse(s)
}
A: 

If you are sure that in all cases there will be only one type you can come up with the following cast:

for (l <- json.asInstanceOf[List[List[String]]]) {...}

Otherwise do a Pattern-Match for all expected cases.

getagrip
Neither does this answer explain why it works nor does it seem to be a general solution to the problem.
ziggystar
+3  A: 

You might have more luck using the lift-json parser, available at: http://github.com/lift/lift/tree/master/framework/lift-base/lift-json/

It has a much richer type-safe DSL available, and (despite the name) can be used completely standalone outside of the Lift framework.

Kevin Wright
+5  A: 

You will have to do pattern matching to traverse the structures returned from the parser.

/*
 * (untested)
 */
def printThem(a: Any) {
  a match {
    case l:List[_] => 
      println("List:")
      l foreach printThem
    case m:Map[_, _] =>
      for ( (k,v) <- m ) {
        print("%s -> " format k)
        printThem(v)
      }
    case x => 
      println(x)
  }
val json = Json.parse(urls)
printThem(json)
mkneissl