Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with nested maps from a JSON string

Tags:

scala

Given a JSON string like this:

{"Locations":
  {"list":
    [
      {"description": "some description", "name": "the name", "id": "dev123"},
      {"description": "other description", "name": "other name", "id": "dev59"}
    ]
  }
}

I'd like to return a list of "id"s from a function parsing the above string. JSON.parseFull() (from scala.util.parsing.json) gives me a result of type Option[Any]. Scala REPL shows it as Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ... and as a beginner in Scala I'm puzzled as to which way to approach it.

Scala API docs suggest "to treat it as a collection or monad and use map, flatMap, filter, or foreach". Top-level element is an Option[Any] however that should be Some with a Map that should contain a single key "Locations", that should contain a single key "list" that finally is a List. What would be an idiomatic way in Scala to write a function retrieving the "id"s?

like image 303
FilipK Avatar asked Dec 09 '22 05:12

FilipK


1 Answers

First of all, you should cast json from Any to right type:

val json = anyJson.asInstanceOf[Option[Map[String,List[Map[String,String]]]]]

And then you may extract ids from Option using map method:

val ids = json.map(_("Locations")("list").map(_("id"))).getOrElse(List())
like image 157
alno Avatar answered Dec 25 '22 11:12

alno