I'm trying to create a function, that takes Json string and path as an input, and returns the data in that path, for e.g. to extract the id
field from the below JSON using Scala, using the path "employee/id"
val json = {
"employee" : {
"id" : "12345",
"department" : "Finance"
}
}
def extractData(json: String, path: String) // returns data for the given path
extractData(json, "employee/id") // returns "12345"
I'm able to extract directly using the code,
val data = Json.parse(jsonData) / "employee" / "id"
I want to extract the data, without hard coding the path, I tried using the below code
val path = "employee/id"
val levels = path.split('/')
val data = levels.foldLeft(parsedJson)((acc, level) => (acc \ level))
I'm getting, Type mismatch
error. I also tried, using other methods with mutable states.
Is there any functional way to do this in Scala?
Scala version = 2.12.10
Play json version = 2.9.0
You need to convert type
JsValue
toJsLookupResult
. You can make it like this: