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\\\/
isnt there an extra \ in the Result ? \t\\\/ instead of \t\\/
"/" is also escaped.
I believe single/double quote marks (', ") are not not escaped, right? Also, when we call JSONObject.toString(), this escape() method is called internally, right?
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().
WHY is "/" escaped? I don't see any reason for it in the JSON specs.
"/" 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.
What happened if we want to pass the special characterss like %,&, space..... Will that also be like \% and \& ?
↓ what should be escaped ↓
end nothing else!