Ra Ka
Ra Ka

Reputation: 3055

Scala, PlayFramework - How to avoid auto escaping character while converting to Json?

I have a String:

val x = """{foo:"value1", bar:"value2"}"""

and I want to convert it into JsString.

val converted = JsString(x)

Now, if i print converted, following result is printed:

"{foo:\"value1\", bar:\"value2\"}"

However, I don't want the \ added in the string. Is there any other way avoid this auto escaping without using string.replace?

Upvotes: 1

Views: 1029

Answers (2)

Cyrille Corpet
Cyrille Corpet

Reputation: 5315

"{foo:"value1", bar:"value2"}"

is not a valid JSON, that's why quotes are escape by JsString. Indeed, how would a JSON parser interpret this, if the internal quotes are not escaped?

If you want a (JVM) String with the JSON object inside, you already have it. If you want a JSON string, representing a JSON object, you MUST have escaping characters.

If you want the JSON object, you can always use

val obj: JsValue = Json.parse("""{foo:"value1", bar:"value2"}""")

Upvotes: 1

vvg
vvg

Reputation: 6385

Try

println(JsString("""{foo:"value1", bar:"value2"}""").value)

Upvotes: 1

Related Questions