extracting data from JSON for a given path using Play JSON

545 views Asked by At

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
1

There are 1 answers

1
Oleg Zinoviev On BEST ANSWER

You need to convert type JsValue to JsLookupResult. You can make it like this:

  val jsonTest = """{
                   |  "employee" : {
                   |    "id" : "12345",
                   |    "department" : "Finance"
                   |    }
                   |}""".stripMargin

  def main(args: Array[String]): Unit = {
      val x = extractData(jsonTest, "employee/id").as[String]
    println(x)
  }

  def extractData(json: String, path: String): JsLookupResult = {
    val jsValue: JsValue = Json.parse(json)
    path.split("/").foldLeft(jsValue.result) { (acc, el) =>
      acc \ el
    }
  }