Scala中解析JSON并获取carDriverMap指定键对应值的方法
Hey there! Since you're new to Scala and working with the older scala.util.parsing.json.JSON library, let's break down exactly how to fetch the value for a specific key in your carDriverMap array. First, a quick note: your original JSON has a tiny typo—"carDriverMap " has an extra space at the end of the key. We'll fix that first because it would break key lookup otherwise.
Step 1: Fix the JSON String
First, correct the key name to remove the trailing space:
val driverCarJSON = """{ "collection": { "listing": [ ], "cars": ["bmw", "ford", "vw"] , "carDriverMap":[{"car1":"driver1"}, {"car2":"driver2"}, {"car3":"driver3"}, {"car4":"driver4"}, {"car5":"driver5"}] } }"""
Step 2: Implement the Lookup Function
The scala.util.parsing.json.JSON library returns loosely typed values (mostly Any), so we'll use pattern matching to safely navigate the JSON structure and find our target key-value pair:
import scala.util.parsing.json.JSON def getDriverByCarKey(targetKey: String): Option[String] = { // Parse the JSON string into an optional top-level map JSON.parseFull(driverCarJSON) match { case Some(topLevel: Map[String, Any]) => // Extract the "collection" object from the top-level map topLevel.get("collection") match { case Some(collection: Map[String, Any]) => // Extract the "carDriverMap" array (list of small maps) collection.get("carDriverMap") match { case Some(driverList: List[Map[String, String]]) => // Find the first map in the list that contains our target key, then get its value driverList.find(_.contains(targetKey)).flatMap(_.get(targetKey)) case _ => None // If carDriverMap isn't a list of string maps } case _ => None // If collection isn't a map } case _ => None // If JSON parsing fails entirely } }
Step 3: Use the Function
You can call this function to get the driver for a specific car key, and handle cases where the key doesn't exist using getOrElse:
// Get driver for "car2" val driver2 = getDriverByCarKey("car2") println(driver2) // Output: Some(driver2) // Get the raw value or a fallback if not found println(driver2.getOrElse("No driver found for this car")) // Output: driver2
Why This Works
JSON.parseFullsafely parses the string and returns anOption[Any](so we avoid nulls)- We use nested pattern matching to verify each level of the JSON structure (top-level map → collection map → carDriverMap list)
findlocates the first map in the list that has our target key, andflatMapextracts its value (wrapped in anOptionto handle missing keys)
Just a heads-up: this library is pretty outdated—modern Scala projects usually use libraries like Circe or Play JSON for type-safe JSON handling. But since you're specifically using this old library, this approach will get the job done!
内容的提问来源于stack exchange,提问作者uniXVanXcel

