我有以下的Scala代码。我的目标是在不知道键有多少个和有多深的情况下提取键的值。
import org.json4s.jackson.JsonMethods._
import org.json4s.{DefaultFormats, JField, JObject, JString, JValue}
object jsonLift {
implicit val formats = DefaultFormats
val js = parse(
"""
{
"url": "imap.yahoo.com",
"credentials": {
"username": "myusername",
"password": "mypassword"
},
"some key":{
"other key": {
"username": "hello"
}
}
}
""")
def getElem(elem: String, json:JValue) = for {
JObject(child) <- json
JField(elem, JString(value)) <- child // this does not return the expected result
// JField("username", JString(value)) <- child // this returns the expected result
} yield value
def main(args: Array[String]) {
val result = getElem("username", js)
println(result)
}
}
上述代码的结果是
List(imap.yahoo.com, myusername, mypassword, hello)
,这不是我期望的结果。我的预期结果是List(myusername, hello)
。然而,如果我直接在
getElem
方法中更改变量elem
为我感兴趣的键(例如:"username"),我将获得预期的结果:List(myusername, hello)
,它们都是键"username"的值。如何通过调用带有JSON键名称作为参数的
getElem
方法来获取预期的值列表?例如:getElem("JSON key", json)
谢谢!
List(myusername, hello)
。 - geo