My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
EscapingExamples  
Examples of escaping strings with special characters
Updated Feb 4, 2010 by fangyid...@gmail.com

Escaping text that contains special characters

JSONObject.escape() escapes quotes,\, /, \r, \n, \b, \f, \t and other control characters. It can be used to escape JavaScript codes.

  String s = "\"foo\" is not \"bar\". specials: \b\r\n\f\t\\/";

  s = JSONObject.escape(s);
		
  System.out.println(s);

Result:

  \"foo\" is not \"bar\". specials: \b\r\n\f\t\\\/
Comment by smartnut...@gmail.com, Jul 27, 2009

isnt there an extra \ in the Result ? \t\\\/ instead of \t\\/

Comment by project member fangyid...@gmail.com, Aug 7, 2009

"/" is also escaped.

Comment by xsga...@gmail.com, Oct 20, 2009

I believe single/double quote marks (', ") are not not escaped, right? Also, when we call JSONObject.toString(), this escape() method is called internally, right?

Comment by project member fangyid...@gmail.com, Oct 21, 2009

Single quote is NOT escaped (we don't have to) but double quote IS escaped. Yes it's true that escape() is called internally in JSONObject.toString().

Comment by mcherm, Nov 9, 2009

WHY is "/" escaped? I don't see any reason for it in the JSON specs.

Comment by project member fangyid...@gmail.com, Nov 13, 2009

"/" is escaped to avoid some issues in html, such as "</" ... Actually we can make it escape "/" only when it's after "<", say "</" to "<\/", but we currently choose to escape all of them to make the code simpler and the performance higher... From some inputs of current JSON.simple users, we may need to improve it to make the some string such as URL look more nicely... Although it's not a violation of JSON spec, we may need to address some usability requirements.

Thanks a lot for the feedback.

Comment by jagadish...@gmail.com, May 11, 2011

What happened if we want to pass the special characterss like %,&, space..... Will that also be like \% and \& ?

Comment by yumaa.ve...@gmail.com, May 26, 2011

↓ what should be escaped ↓

end nothing else!


Sign in to add a comment
Powered by Google Project Hosting