2

I'm sorry if this question is too simple, I'm just starting with Scala.

I was trying to parse some JSON in Scala, and I'm having a bit of trouble to understand what is going on below:

scala> import scala.util.parsing.json.JSON
scala> val x = JSON.parseFull("""{"name": "x",  "lang": "en"} """)

x: Option[Any] = Some(Map(name -> x, lang -> en))

Now, as parseFull returns an Option[Any], and as I know that it really contains a value, I can write:

scala> x.get
res6: Any = Map(name -> x, lang -> en)

How can I process this Any result? What I'd like is to access directly to the key or the value, doing something similar to x.get("name").

Thanks a lot!

Jacob
  • 1,886
  • 2
  • 25
  • 40
  • Try looking at this question - http://stackoverflow.com/questions/4170949/how-to-parse-json-in-scala-using-standard-scala-classes - Basically your problem is that your variable that parseFull() is stored into can't know the type of structure that is being created, so its being made as an "Any" object. You can get around this by wrapping it in various error handling conditions. – Ren Feb 09 '14 at 23:03

1 Answers1

6

So if you're using the pure Scala parsing options, you'll get an Any that you can translate back into a map:

scala> x.get.asInstanceOf[Map[String,String]]
res6: Map[String,String] = Map(name -> x, lang -> en)

scala> x.get.asInstanceOf[Map[String,String]].get("lang")
res7: Option[String] = Some(en)

scala> x.get.asInstanceOf[Map[String,String]].get("lang").get
res8: String = en

It's a bit cumbersomee; there are a few libraries that impose a cleaner interface to handle some of the conversions such as

And I'm sure others.

Damiya
  • 824
  • 6
  • 12