I have the following code in Scala. My goal is to extract the value(s) of a key without knowing how many and how deep they are.
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)
elem
getElem
List(myusername, hello)
getElem
getElem("JSON key", json)
Change getElem
to
def getElem(elem: String, json:JValue) = for {
JObject(child) <- json
JField(`elem`, JString(value)) <- child
} yield value
Without the backticks around elem
on the RHS, you are binding the first element of type JField = (String, JValue)
to a new name elem
and shadowing the method parameter elem