簡體   English   中英

在 Scala 中的 JsObject 中查找 JsValue

[英]Find a JsValue in JsObject In Scala

如何創建一個在 JsObject 中找到 JsValue 的遞歸函數,例如:函數輸入:JsObject 和路徑作為字符串示例:

JsObject 的輸入:

{
"name": "Zvi"
parents: {
 "father": {
  "name": "myFatherName",
  "dob": "10/10/70"
  }
}
}

和路徑示例:

  1. path = notExistsField 輸出將為 None
  2. path = name 輸入將是 Some("Zvi")
  3. 路徑 = 父母輸出將是
   Some({
 "father": {
  "name": "myFatherName",
  "dob": "10/10/70"
  }
})
  1. parent.father 輸出將是:
Some({
  "name": "myFatherName",
  "dob": "10/10/70"
  })
  1. parent.father.name 輸出將是“myFatherName”

測試示例:

"deepSearch" - {
      val payload: JsObject = Json.parse(
        """{
          |  "key1": 1,
          |  "key2": {
          |    "key1": "value21",
          |    "key2": {
          |      "key1": 221
          |    }
          |  },
          |}""".stripMargin).as[JsObject]
      "found" - {
        "nested" in {
          // In Nested Object
          service.deepSearch(payload,"key2.key1").get shouldBe JsString("value21")
          service.deepSearch(payload,"key2.key2.key1").get shouldBe JsNumber(221)
          service.deepSearch(payload,"key2.key2").get shouldBe Json.parse("{\"key1\": 221}")
        }
        "top-level" in {
          service.deepSearch(payload,"key1").get shouldBe JsNumber(1)
        }
      }
      "not found" - {
        "nested" in {
          service.deepSearch(payload,"key2.key2.key1.notExists").isEmpty shouldBe true
          service.deepSearch(payload,"key2.key2.notExists").isEmpty shouldBe true
        }
        "top-level" in {
          service.deepSearch(payload,"Boom").isEmpty shouldBe true
        }
      }

    }

我做了以下實現,有沒有更漂亮的代碼的建議

def deepSearch(payload: JsValue, path: String): JsLookupResult = {
    path indexOf (".") match {

      // For the Base case:
      case base if base < 0 => (payload \ path)

      // For the Step case:
      case found if found >= 0 =>
        val untilFirstDot = path.substring(0, found)
        (payload \ untilFirstDot) match {
          case JsDefined(newPayload) => deepSearch(newPayload, path.substring(found + 1))
          case undefined: JsUndefined => undefined
        }
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM