I am new to scala and still needs to learn a lot. but for the time being I have this json object :
driverCarJSON = """{
"collection": {
"listing": [
],
"cars": ["bmw", "ford", "vw"]
,
"carDriverMap" :[{"car1":"driver1"},
{"car2":"driver2"},
{"car3":"driver3"},
{"car4":"driver4"},
{"car5":"driver5"}]
}
}"""
I am trying to access the value of the keys in carDriverMap. So if I want the value of "car2" it should return "driver2"
Now, I am parsing this json using this:
scala.util.parsing.json.JSON.parseFull(driverCarJSON)
This returns
Some(Map(collection -> Map(listing -> List(), cars -> List(bmw, ford, vw), carDriverMap -> List(Map(car1 -> driver1), Map(car2 -> driver2), Map(car3 -> driver3), Map(car4 -> driver4), Map(car5 -> driver5)))))
I am stuck here what should i do?
I have seen this solution using a function
def getValue(parsedJson : Option[Any] , key:String): String ={
parsedJson match {
case Some(m : Map[String,Any]) => m(key) match {
case d:String => d
}
}
}
and then calling it getValue(driverCarJSON , carDriverMap["collection"][2]["car2"])
but when i print it nothing gets printed.
Thanks
Update 2024
If you don't care about what used to work for 2.11, consider using e.g.
Original answer from 2018
This here works with 2.11 and separate parser-combinators dependency:
val driverCarJSON = """{
"collection": {
"listing": [
],
"cars": ["bmw", "ford", "vw"]
,
"carDriverMap" :[{"car1":"driver1"},
{"car2":"driver2"},
{"car3":"driver3"},
{"car4":"driver4"},
{"car5":"driver5"}]
}
}"""
val parsedJson = scala.util.parsing.json.JSON.parseFull(driverCarJSON).get
val d2 = parsedJson
.asInstanceOf[Map[String, Any]]
.apply("collection")
.asInstanceOf[Map[String, Any]]
.apply("carDriverMap")
.asInstanceOf[List[Map[String, String]]]
.apply(1)("car2")
println(d2) // output: driver2
But I personally find the API not terribly well thought out. I couldn't find any way to avoid all the ugly and unnecessary asInstanceOf
s. This has been deprecated very long ago, so please consider using something newer like json4s
, it does not suffer from the repetitive asInstanceOf
s.