I found many posts about escaping string but no about de-escaping one.
Using Scala Play, my controller accept a JSON as a request. I extract a string from it via:
val text: play.api.libs.json.JsValue = request.body.\("source")
If I print text.toString
I get e.g.
"Hello\tworld\nmy name is \"ABC\""
How can I transform this escaped text into normal one? The result should look like
Hello world
my name is "ABC"
Up to this point, I've tried an approach like it follows:
replaceAll("""\\t""", "\t")
However, creating all possible escaping rules may be too complicated. So my question is: How to do that easily? Possibly using standard library. Java solutions are also possible.
In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal.
Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark (").
JSON is pretty liberal: The only characters you must escape are \ , " , and control codes (anything less than U+0020). This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character.
There are interpolations which allow you to transform Strings into formatted and/or escaped sequences. These interpolations like s"..."
or f"..."
are handled in StringContext.
It also offers a reverse function:
val es = """Hello\tworld\nmy name is \"ABC\""""
val un = StringContext treatEscapes es
This isn't an answer for unescaping strings in general, but specifically for handling JsValue
:
text match {
case JsString(value) => value
case _ => // what do you want to do for other cases?
}
You can implement unescape in this way:
def unescapeJson(s: String) = JSON.parse('"' + s + '"') match {
case JsString(value) => value
case _ => ??? // can't happen
}
or use StringEscapeUtils
from Apache Commons Lang (though this is a rather large dependency).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With