You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala中解析JSON并获取carDriverMap指定键对应值的方法

获取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.parseFull safely parses the string and returns an Option[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)
  • find locates the first map in the list that has our target key, and flatMap extracts its value (wrapped in an Option to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:22:09