给定一个像这样的 JSON 字符串:
{"Locations":
{"list":
[
{"description": "some description", "name": "the name", "id": "dev123"},
{"description": "other description", "name": "other name", "id": "dev59"}
]
}
}
我想从解析上述字符串的函数返回一个“id”列表。
JSON.parseFull()
(来自 scala.util.parsing.json
)给我一个 Option[Any]
类型的结果。 Scala REPL 将其显示为 Some(Map(Locations -> Map(list -> List(Map(id -> dev123, ...
并且作为 Scala 的初学者,我对使用哪种方法感到困惑。Scala API docs 建议“将其视为集合或 monad,并使用 map、flatMap、filter 或 foreach”。顶级元素是一个 Option[Any] ,但是它应该是 Some ,带有一个应该包含单个键“Locations”的 Map,应该包含一个最终是 List 的单个键“list”。在 Scala 中编写检索“id”的函数的惯用方法是什么?
最佳答案
首先,您应该将 json 从 Any 转换为正确的类型:
val json = anyJson.asInstanceOf[Option[Map[String,List[Map[String,String]]]]]
然后你可以使用
map
方法从 Option 中提取 ids:val ids = json.map(_("Locations")("list").map(_("id"))).getOrElse(List())
关于scala - 使用来自 JSON 字符串的嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7727773/