How to get rid of extra escape characters while doing json transformation using scala play framework?

457 views Asked by At

I want to update some of the fields present in a json string and I am using play framework in scala.But when I am updating the json few escape string characters are getting introduced.And I dont want these charcters after the json transformation.below are some code samples.

val jsonStringAsJsValue = Json.toJson("""{"counter_holders": {"Peter": 25}}""")
//play.api.libs.json.JsValue = "{\"counter_holders\": {\"Peter\": 25}}"

val jsonTransformer = (__ \"counter_holders" ).json.put(Json.toJson("""{"*****":25}"""))
//JsObject

jsonStringAsJsValue .transform(jsonTransformer).get.as[JsValue]
//Now getting the below string
//{"counter_holders":"{\"*****\":25}"}
//But I need this string
//{"counter_holders":"{"*****":25}"}

Either I convert resulting value to JSvalue or JSString escape charcters are getting introduced.Any help on this will be really nice.

1

There are 1 answers

0
Martijn On BEST ANSWER

Json.toJson is for converting a string to a json value -- a json encoded string. You don't want that, you want to parse the strings as json. For that, use Json.parse

You'll end up with

val jsonStringAsJsValue = Json.parse("""{"counter_holders": {"Peter": 25}}""")
val jsonTransformer = (__ \"counter_holders" ).json.put(Json.parse("""{"*****":25}"""))
jsonStringAsJsValue.transform(jsonTransformer).get.as[JsValue]