Search code examples
scalaplay-json

Play json: parse json value to string without quotes


I have a json object lets say

{
    "company":"77160"
}

And I parse it in Scala with play.api.libs.json like this:

cols = Json.parse(line).as[JsObject]
val company = s"${cols("company")}".toString

yet the returned string has double quotes (i.e., ""77160"") What gives? How do I get a normal string ((i.e., "77160")) without reparsing it myself (with replace function for example).


Solution

  • You have to call .as[String] on cols("company"). See https://www.playframework.com/documentation/2.8.x/ScalaJson#Using-JsValue.as/asOpt.

    Like so:

    cols = Json.parse(line).as[JsObject]
    val company = cols("company").as[String]
    

    In case you're wondering what's happening under the hood, the as method is of type JsValue.as[T](implicit fjs: Reads[T]): T and it uses implicits to find an implicit converter for T. Since we are using as[String] here, it will search for an implicit converter that fits that type and since play already defined it in its library, it will use that converter.