Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where can I find a list of escape characters required for my JSON ajax return type?

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.

like image 444
Blankman Avatar asked Jun 11 '09 20:06

Blankman


People also ask

What characters must be escaped in JSON?

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.

How do you escape a character in JSON Java?

The simplest approach is to replace quotes with the appropriate escape sequence: String payload = "{\"message\":\"" + message.


2 Answers

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 
like image 142
Pashec Avatar answered Sep 22 '22 05:09

Pashec


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.

like image 22
Chris Nielsen Avatar answered Sep 18 '22 05:09

Chris Nielsen