Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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":{}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[{"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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading