I have an ASP.NET MVC action that is returning a JSON object.
The JSON:
{status: "1", message:"", output:"<div class="c1"><div class="c2">User generated text, so can be anything</div></div>"}
Currently my HTML is breaking it. There will be user generated text in the output field, so I have to make sure I escape ALL things that need to be escaped.
Does someone have a list of all things I need to escape for?
I'm not using any JSON libraries, just building the string myself.
In JSON the only characters you must escape are \, ", and control codes. Thus in order to escape your structure, you'll need a JSON specific function.
The simplest approach is to replace quotes with the appropriate escape sequence: String payload = "{\"message\":\"" + message.
Take a look at http://json.org/. It claims a bit different list of escaped characters than Chris proposed.
\" \\ \/ \b \f \n \r \t \u four-hex-digits
Here is a list of special characters that you can escape when creating a string literal for JSON:
\b Backspace (ASCII code 08) \f Form feed (ASCII code 0C) \n New line \r Carriage return \t Tab \v Vertical tab \' Apostrophe or single quote \" Double quote \\ Backslash character
Reference: String literals
Some of these are more optional than others. For instance, your string should be perfectly valid whether you escape the tab character or leave in a tab literal. You should certainly be handling the backslash and quote characters, though.
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