Scala – Couldn't remove double quotes for Key -> value "{}" braces while building Json

Scala – Couldn’t remove double quotes for "{}" braces while building Json

import scala.util.Random
import math.Ordered.orderingToOrdered
import math.Ordering.Implicits.infixOrderingOps
import play.api.libs.json._
import play.api.libs.json.Writes
import play.api.libs.json.Json.JsValueWrapper

val data1 = (1 to 2)
.map {r => Json.toJson(Map(
                "name" -> Json.toJson(s"Perftest${Random.alphanumeric.take(6).mkString}"),
                "domainId"->Json.toJson("343RDFDGF4RGGFG"),
                "value" ->Json.toJson("{}")))}
val data2 = Json.toJson(data1)
println(data2)

Result :
[{"name":"PerftestpXI1ID","domainId":"343RDFDGF4RGGFG","value":"{}"},{"name":"PerftestHoZSQR","domainId":"343RDFDGF4RGGFG","value":"{}"}]

Expected :
"value":{}

[{"name":"PerftestpXI1ID","domainId":"343RDFDGF4RGGFG","value":{}},{"name":"PerftestHoZSQR","domainId":"343RDFDGF4RGGFG","value":{}}]

Please suggest a solution

>Solution :

You are giving it a String so it is creating a string in JSON. What you actually want is an empty dictionary, which is a Map in Scala:

val data1 = (1 to 2)
  .map {r => Json.toJson(Map(
                  "name" -> Json.toJson(s"Perftest${Random.alphanumeric.take(6).mkString}"),
                  "domainId"->Json.toJson("343RDFDGF4RGGFG"),
                  "value" ->Json.toJson(Map.empty[String, String])))}

More generally you should create a case class for the data and create a custom Writes implementation for that class so that you don’t have to call Json.toJson on every value.

Leave a Reply