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

123 Views Asked by At

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

1

There are 1 best solutions below

5
Tim On BEST ANSWER

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.


Here is how to do the conversion using only a single Json.toJson call:

import play.api.libs.json.Json

case class MyData(name: String, domainId: String, value: Map[String,String])
implicit val fmt = Json.format[MyData]

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

The value field can be a standard type such as Boolean or Double. It could also be another case class to create nested JSON as long as there is a similar Json.format line for the new type.

More complex JSON can be generated by using a custom Writes (and Reads) implementation as described in the documentation.