Search code examples
javaarraysjsonscalajson4s

use Scala to get JSON data in lower levels


I'm a beginner of Scala, and I have JSON data formatted like below:

{
    "index_key": {
        "time":"12938473",
        "event_detail": {
            "event_name":"click",
            "location":"US"
        }
    }
}

I'm trying to get the content of "index_key" and extract the content of second level as a new JSON objet and initiate a class based on the second level data.

{
    "time":"12938473",
    "event_detail": {
        "event_name":"click",
        "location":"US"
    }
}

I tried to use json4s to extract from the above json to be a Event class, but how to get rid of the "index_key" which is the first level key?

 case class Detail(event_name: String, location: String)
 case class Event(time: String, event_detail: Detail)

 json.extract[Event]

I've read json4s documentation, and also http://www.scala-lang.org/api/2.10.3/index.html#scala.util.parsing.json.JSON$, but still don't quite get it, as it seems the pre-defined json should be fit for the parser?

Could anyone please tell me how to get the second level data (or any lower level) of the json structure?


Solution

  • You can use \ to get to the object you want to extract:

    val json = parse(str) \ "index_key"
    json.extract[Event]