【发布时间】:2016-12-13 05:40:58
【问题描述】:
我在 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,并使用我感兴趣的键(作为字符串)(例如:“用户名”),我会得到预期的结果:List(myusername, hello)这是键“用户名”的所有值。
如何通过以 JSON 键的名称作为参数调用方法 getElem 来获得预期的值列表?例如:getElem("JSON key", json)
谢谢!
【问题讨论】:
-
预期结果应该是
List(myusername, hello)